问题
So, I just came across the fact that rails does not support referential integrity regarding foreign keys and was fairly surprised. So, what's the best way to manage this? Is there a "rails" way for dealing with referential integrity?
Ideally the app should not have to deal with all this; the db should. I was looking at plugins like foreigner. I wonder if this method has some shortcomings. How is this normally dealt with in rails?
回答1:
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.
回答2:
You can provide programmatic referential integrity by using
,:dependent => :restrict
on your has_one and has_many statements!
Blog describing this and how to check before error occurs
Relevant Active Record docs
来源:https://stackoverflow.com/questions/3438731/referential-integrity-in-rails