1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00
Files
til/rails/determine-the-configured-primary-key-type.md

1.2 KiB

Determine The Configured Primary Key Type

I noticed an interesting helper function in the database migration generated by bin/rails active_storage:install.

class CreateActiveStorageTables < ActiveRecord::Migration[8.0]
  def change
    # Use Active Record's configured type for primary and foreign keys
    primary_key_type, foreign_key_type = primary_and_foreign_key_types

    # ...
  end

  private

    def primary_and_foreign_key_types
      config = Rails.configuration.generators
      setting = config.options[config.orm][:primary_key_type]
      primary_key_type = setting || :primary_key
      foreign_key_type = setting || :bigint
      [ primary_key_type, foreign_key_type ]
    end
end

The primary_and_foreign_key_types method looks in the generators config for the ORM (:active_record) to determine the configured :primary_key_type. By default this will return nil. This method then uses :primary_key as a fallback value which will be bigint. That's why the foreign_key_type falls back to :bigint.

If desired, this can be manually configured in config/application.rb like shown in the ActiveRecord Migrations docs.