Should I use rails 4.2 add foreign_key or not?
Asked Answered
B

1

7

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?

Burp answered 28/1, 2015 at 9:14 Comment(3)
It's not simply limited to combine model:reference and add_index. It's about adding foreign key constraint to the database. There were no such option before without raw sql or additional gems (such foreiner).Putt
but the effect (i.e connecting 2 models in relation) is the same, right? (I have little knowledge about databases). How does foreign key constraint vary from integer column with id and index on it?Burp
You may or may not use add_foreign_key method. But, you should either use model:reference or model_id:integer:index parameters when generating migration. Without this you will not be able to connect two models.Putt
B
4

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.

Burp answered 12/2, 2015 at 11:2 Comment(1)
To my knowledge, Rails doesn't create a foreign key constraint by default. See: api.rubyonrails.org/v5.2.0/classes/ActiveRecord/…Asphaltite

© 2022 - 2024 — McMap. All rights reserved.