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?

Tim Down
  • 318,141
  • 75
  • 454
  • 536
Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102
  • 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). – bronislav Jan 28 '15 at 09:37
  • 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? – Filip Bartuzi Jan 28 '15 at 09:42
  • 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. – bronislav Jan 28 '15 at 10:02

1 Answers1

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.

Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102
  • 1
    To my knowledge, Rails doesn't create a foreign key constraint by default. See: http://api.rubyonrails.org/v5.2.0/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference – fkoessler May 30 '18 at 09:52