Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 824
Neil Avatar asked Jan 06 '15 23:01

Neil


People also ask

How do you name migration in Rails?

Migrations should be: Camel cased or Snake cased. start with an action (i.e. create, add, remove, etc) The name of the table should be the last word and it should be plural.

How do I add a reference column in Rails?

When you already have users and uploads tables and wish to add a new relationship between them. Then, run the migration using rake db:migrate . This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.

How do I rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

Do you need foreign keys in Rails?

You do not need a foreign key constraints for ActiveRecord to correctly map the relationships. You can use validations to have the Rails app ensure data integrity.


1 Answers

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 

Inside a create_table block

t.references :feature, foreign_key: {to_table: :product_features} 
like image 192
schpet Avatar answered Nov 07 '22 03:11

schpet