By release of rails 4.2 add_foreign_key method was introduced. As far as I understand it is used as combo of migration with model:references
and add_index
.
Let's say I only use PostreSQL. (add_foreign_key
is limited to MySQL and PostreSQL). Should stop using migration model:references
with add_index
and start using add_foreign_key
only?. If yes/no, why?. What are benefits of new add_foreign_key
method? Is it worth to swap?
If you want you can always use add_index on the fields that you want as foreign keys. Or you can write your migrations in SQL or perhaps even force rails to do the foreign keys somehow. But the thing is you won't even look for a way to do it if you don't know rails is not doing itin the first place.
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.
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.
Foreign key constraints can help with referential integrity (you can't insert data belonging to a book that doesn't exist for example). Foreign keys also provide database level referential integrity as opposed to application level (model validation) integrity.
The Rails team felt it important enough that they now automatically create foreign keys whenever you use references in generating your migrations.
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