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.
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.
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.
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.
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.
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:
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:
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