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.
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.
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.
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.
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.
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