Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activerecord migrations, making t.references correctly point to a custom ID type, string not integer?

Below I have a migration for the "test" model which uses it's own primary key, a String instead of an Integer.

    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 the "client" model that t.references test.

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

          t.references :test,   null: false

          t.timestamps
        end
      end
    end

The issue is that t.references assumes it's an integer id.

    # == 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 wrong as Test.id is a string.

Is there some magic I need to do to have the t.references "know" that it's a string based on the model or something?

Thanks.

like image 520
Jason Ellis Avatar asked Dec 18 '22 00:12

Jason Ellis


1 Answers

Add this to the migration with the references:

type: :string

The reference column type. Defaults to :integer.

You can read more here.

like image 153
JollyProgrammer Avatar answered Apr 08 '23 10:04

JollyProgrammer