foreigner foreign_key on a different column in source and target table.

In the foreigner gem, you can specify the foreign_key column on the source table by using the column option.

class Cats < ActiveRecord::Migration
  def change
    create_table :cats do |t|
      t.integer :color_id
      t.integer :second_color_id

      t.timestamps
    end
    add_foreign_key :cats, :colors, column: :second_color_id
  end
end

But what about the target table? This can be accomplished using the primary_key option.

class Dogs < ActiveRecord::Migration
  def change
    create_table :dogs do |t|
      t.integer :color_id
      t.integer :breed_name

      t.timestamps
    end
    add_foreign_key :dogs, :breed, column: :breed_name, primary_key: :name
  end
end

Of course, the model has to change as well:

class Dog < ActiveRecord::Base
  belongs_to :breed, primary_key: :name
end

One Reply to “foreigner foreign_key on a different column in source and target table.”

Comments are closed.