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?
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.
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.
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With