Rails Migration: add_reference to Table but Different Column Name For Foreign Key Than Rails Convention

Neil picture Neil · Jan 7, 2015 · Viewed 53.1k times · Source

I have the following two Models:

class Store < ActiveRecord::Base
    belongs_to :person
end

class Person < ActiveRecord::Base
    has_one :store
end

Here is the issue: I am trying to create a migration to create the foreign key within the people table. However, the column referring to the foreign key of Store is not named store_id as would be rails convention but is instead named foo_bar_store_id.

If I was following the rails convention I would do the migration like this:

class AddReferencesToPeople < ActiveRecord::Migration
  def change
    add_reference :people, :store, index: true
  end
end

However this will not work because the column name is not store_id but is foo_bar_store_id. So how do I specify that the foreign key name is just different, but still maintain index: true to maintain fast performance?

Answer

schpet picture schpet · Feb 13, 2017

in rails 5.x you can add a foreign key to a table with a different name like this:

class AddFooBarStoreToPeople < ActiveRecord::Migration[5.0]
  def change
    add_reference :people, :foo_bar_store, foreign_key: { to_table: :stores }
  end
end