Migrations Activerecord, what makes t.references correctly point to a custom identifier type, string not integer?

Below I have a migration for a “test” model that uses its own primary key, instead of String instead of integers.

    class CreateTest < ActiveRecord::Migration[5.1]
      def change
        create_table :test, id: false do |t|

          t.string  :id,          primary_key: true

          t.timestamps
        end        
      end
    end

Now we have a “client” model that is testing t.references.

    class CreateClients < ActiveRecord::Migration[5.1]
      def change
        create_table :clients do |t|

          t.references :test,   null: false

          t.timestamps
        end
      end
    end

The problem is what the t.referencesinteger id assumes.

    # == Schema Information
    #
    # Table name: clients
    #
    #  id         :integer          not null, primary key
    #  test_id    :integer          not null
    #  created_at :datetime         not null
    #  updated_at :datetime         not null

This is obviously not true as it Test.idis a string.

Is there any magic I need to do to t.references“know” that this is a model-based string or something like that?

Thank.

+4
source share
3 answers

references:

type: :string

. : integer.

.

+5

type :

t.references :test, type: :string, null: false
+4

Could you use:

class CreateClients < ActiveRecord::Migration[5.1]
  def change
    create_table :clients do |t|

      t.string :test_id,   null: false

      t.timestamps
    end
  end
end
+2
source

Source: https://habr.com/ru/post/1695212/


All Articles