5

Rails does not support referential integrity foreign keys. How do I manage this?

Ideally the app should not have to deal with this; the database should. Do plugins like Foreigner have shortcomings? How is this dealt with?

philipxy
  • 14,867
  • 6
  • 39
  • 83
akula1001
  • 4,576
  • 12
  • 43
  • 56

2 Answers2

7

It's a design decision for Rails ActiveRecord.

I consider stored procedures and constraints vile and reckless destroyers of coherence. No, Mr. Database, you can not have my business logic. Your procedural ambitions will bear no fruit and you'll have to pry that logic from my dead, cold object-oriented hands.

Choose a single layer of cleverness - DHH

So the answer is that referential integrity handled by the DB is not the Rails way at all.

Jonas Elfström
  • 30,834
  • 6
  • 70
  • 106
  • 1
    If you are looking for the article, it's hidden in this page http://david.heinemeierhansson.com/arc/2005_09.html – ytbryan Aug 09 '18 at 13:25
1

If you are unfamiliar with referential integrity, it is the way for relational databases to prevent the accidental deletion of records that are pointed to by other records.

You can do this programmatically using rails referential integrity by adding the following to your has_one or has_many clause:

,:dependent => :restrict_with_error

If instead you want all of the children records to be destroyed with the parent record, use this on your has_one or has_many clause:

,:dependent => :destroy

Active record has many options for dealing with dependent records. see:

Active Record docs

Active Record guide

Taylored Web Sites
  • 1,017
  • 1
  • 9
  • 15