What's the proper way of adding a FK relationship in rails AFTER the tables have been created? I've defined my relationship in my model, but do I have to add the [foreigntable]_id field to the table myself using generate migration? Or is there another option?
In Rails 5, adding foreign key constraints was added to have the database protect the integrity of associated data. Once a foreign key constraint is defined, your database will not allow you to remove records that are required by other tables.
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
It adds a multi-column index on columns one and two in resources table. The advantage of multi-column index is that it helps when you have a query with conditions on those multiple columns.
You definitly need to create a new migration:
rails g migration add_foreign_key_to_model_name_pluralized foreigntable_id:integer
example:
rails g migration add_foreign_key_to_users profile_id:integer
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