Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add_foreign_key vs add_reference in rails

What is the difference between "add_foreign_key" and "add_reference" methods in rails?

According to rails official guide all I understand is that they both are used to create foreign key constraint between two tables.

like image 796
Pradhumn Sharma Avatar asked Oct 21 '18 11:10

Pradhumn Sharma


People also ask

What is add_ foreign_ key rails?

Rails provides add_foreign_key to add foreign key constraint for a column on a table. It also provides remove_foreign_key to remove the foreign key constraint.

Do you need foreign keys in Rails?

Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.

How do you delete a column in Rails?

The change method can be used to drop a column in Rails 4 applications, but should not be used in Rails 3. I updated my answer accordingly. You can also use remove_column :table_name, :column_name, :type, :options within the change method, since if you specify the type reverting the migration is possible.


1 Answers

add_foreign_key - adds a new foreign key. from_table is the table with the key column, to_table contains the referenced primary key.

add_reference - is meant as a shortcut for creating a column, index and foreign key at the same time.

What is foreign key - a foreign key is a field or group of fields in a table that uniquely identifies a row in another table.

like image 106
Philidor Avatar answered Sep 20 '22 14:09

Philidor