Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding foreign key after app creation in Rails

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?

like image 280
James Avatar asked Feb 06 '11 00:02

James


People also ask

How does foreign key work in Rails?

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.

What is the difference between Has_one and Belongs_to?

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.

What does Add_index do in Rails?

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.


1 Answers

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
like image 149
apneadiving Avatar answered Sep 23 '22 13:09

apneadiving