Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are foreign keys in Rails generally avoided?

Rails has no way of creating foreign keys in migrations (there are plugins to do this, however). There are also plenty of cascading options so you can get cascading deletes, for example.

With all of these options built in, is it worth creating foreign keys in the database? Is this something Rails developers normally avoid or what? You'd think if it was a recommended practice that Rails would natively support it.

like image 470
ryeguy Avatar asked Mar 03 '10 17:03

ryeguy


People also ask

Why foreign key is not recommended?

Having active foreign keys on tables improves data quality but hurts performance of insert, update and delete operations. Before those tasks database needs to check if it doesn't violate data integrity. This is a reason why some architects and DBAs give up on foreign keys at all.

Are foreign keys always necessary?

Note that foreign keys are not mandatory, and a table may have no foreign keys. Conversely, every column in a table may have a foreign key constraint.

Do foreign keys hurt performance?

It's a common mistake to avoid creating foreign keys in a database because they negatively impact the performance. It is true that foreign keys will impact INSERT, UPDATE and DELETE statements because they are data checking, but they improve the overall performance of a database.

How can foreign key constraints be prevented?

To disable a foreign key constraint for INSERT and UPDATE statements. In Object Explorer, expand the table with the constraint and then expand the Keys folder. Right-click the constraint and select Modify. In the grid under Table Designer, select Enforce Foreign Key Constraint and select No from the drop-down menu.


1 Answers

Just adding to John Topley's answer, I did a bit of research and found some of DHH's thoughts on the topic, which make for an interesting read:

  • (Jun 2006) DHH replies to Teflon Ted's blog post Should we drink DHH's Kool-Aid?
  • (Feb 2006) DHH replies in the comments (search for 'Good rant') to someone's rant about Rails
  • (May 2006) DHH replies to someone's request for migrations to support foreign keys
  • (Jan 2006) DHH explains why model associations don't belong in schema.rb

I couldn't find DHH referring to the database as a "giant hash", so maybe John is paraphrasing a different quote. I'd love to read a more up-to-date version of DHH's opinion.

I didn't find too many opinions from other people written in the last couple of years. Here are the ones I found:

  • (July 2011) CodeGenesys explain why and how they use foreign keys in Rails
  • (Jan 2008) a blog post entitled You Should Use Foreign Key Constraints in Rails
  • (Nov 2007) a useful blog post which contains more useful research on the pros and cons of foreign keys
like image 116
Adam Spiers Avatar answered Sep 25 '22 09:09

Adam Spiers