Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use rails 4.2 add foreign_key or not?

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?

like image 734
Filip Bartuzi Avatar asked Jan 28 '15 09:01

Filip Bartuzi


People also ask

How do I add a foreign key in Ruby on Rails?

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.

How do I add a reference column in rails?

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.

What is a foreign key constraint 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.


1 Answers

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.

like image 106
Filip Bartuzi Avatar answered Oct 13 '22 00:10

Filip Bartuzi