Ever since I started using Rails I've been wanting a way to enforce referential integrity in the database. The Rails philosophy is to keep business logic out of the database and do it in Ruby. All those nifty validation methods are meant to take care of that. That means no foreign key constraints in the database - just use the rails validations.
But which validations to use? The thing that's always frustrated me is that there isn't a validation to enforce that a foreign key references a record that exists. Sure,
validates_presence_of will make sure you have a foreign key that isn't nil. And
validates_associated will tell you if the record referenced by that key passes its own validations. But that is either too little or too much, and what I want is in the middle ground. So I decided it was time to roll my own.
class Tagging < ActiveRecord::Base belongs_to :tag belongs_to :taggable, :polymorphic => true validates_existence_of :tag, :taggable belongs_to :user validates_existence_of :user, :allow_nil => true end
The above example shows all the interesting bits. You can validate a simple belongs_to association, or one that is polymorphic. You can also use the
:allow_nil option to allow for an optional foreign key. If the foreign key is non-nil, then the referenced record must exist.
validates_existence_of only works for a
Try it out for yourself:
$ script/plugin install http://svn.hasmanythrough.com/public/plugins/validates_existence/
Caveat lector: I've only tried this out on edge, but it should work fine on 1.2.3. Please let me know if you have problems with it.
If there is enough interest I'll submit this as a patch to core.