Validate your existence

— July 14, 2007 at 17:16 PDT

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.

Enter validates_existence_of.

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

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.

Of course validates_existence_of only works for a belongs_to association.

Try it out for yourself:

$ script/plugin install

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.

30 commentsassociations, rails

  1. Aaron Pfeifer2007-07-14 18:36:02

    Great work, Josh! I remember running into this problem when I had first started Rails and could never figure out what the best way was to do this. Should I validatespresenceof :association, validatespresenceof :associationid, validatesassociated :association, etc. I think this plugin will definitely help newcomers and existing developers alike.

    I suppose the only possible downside to validating foreign keys is that you have an extra call to the database every time you validate a record. I suppose there's no way around that besides caching, but it's something to keep in mind.

  2. Josh Susser2007-07-14 19:03:58

    Aaron: Thanks. Yes, I think this will help simplify things a lot too.

    I know there is some overhead for hitting the db to check for the exisitence. I made a patch that speeds things up a little bit (like 5%), but even without that it may not be that bad. validates_uniqueness_of hits the db to do a similar test, and this isn't any worse than that.

  3. Claudio Poli2007-07-14 19:15:04

    Josh, one word: thanks!

  4. badcarl2007-07-14 19:44:11

    This makes way too much sense.

  5. mattly2007-07-14 20:47:28

    great plugin josh. I'd suggest you submit a patch to core anyway, maybe Rick will sneak it in :)

  6. Ron Green2007-07-14 22:44:01

    Wonderful job Josh. I too wrestled with validatespresenceof vs validates_associated seeking a way to enforce referential integrity, but ultimately found neither satisfactory.

    This is the right approach and needs to be added to the core. Thanks!

  7. Tom2007-07-14 23:02:39

    validates existence + allow nil = validates presence

    validates existence - allow nil = validates presence + associated

    Am I wrong? What does this plugin make easier?

  8. Hugh2007-07-14 23:06:03

    Thank You

  9. jason2007-07-15 00:30:40

    Tom: validates existence works on the field... it does not go out and check if the record referenced by that field actually exists... rails works on assumptions - which is fine 95% of the time

  10. Josh Susser2007-07-15 04:53:01

    Tom: You have it sort of backward. validates_existence_of - allow_nil = validates_presence + require existence

    validates_existence and validates_associated aren't very similar. validates_associated works on the in-memory AR object, so if it never gets written to the db, you're hosed.

    validates_existence_of + allow_nil is really where the money is at. You can't do that with validates_presence_of.

    and jason, you have it totally backward. validates_existence_of does check the db to see that the record exists.

  11. crayz2007-07-15 05:08:42

    Man I was just about to go try to write this the other day, but didn't quite have the time or skill. Gotta give it a test tomorrow, but I'll assume it works and say thanks, it'll be a lifesaver!

  12. Clement Joubert2007-07-15 08:11:23

    Thanks a lot, this is a really good plugin. Having it integrated to the core would be much appreciated, but maybe altering the existing validates presence should be enough ?

  13. Andrew France2007-07-15 10:40:38

    What's the problem with using proper foreign keys in the DB? Enforcing key constraints is not even a business logic problem, it's a data storage one.

  14. Josh Susser2007-07-15 14:46:09

    Andrew: It's not a problem putting foreign key constraints in the DB. I know lots of people who do that, and I've done it myself on occasion. However, that doesn't integrate well with everything else you're doing in Rails. If you violate that constraint, what you get is an exception when you try to save the model object. That's ok for starters, but, you can't use the #valid? method on a model to see if its references are, you can't change the error message, etc.

  15. Sharon Rosner2007-07-15 17:27:00

    I don't think you can really call it enforcing referential integrity in the database. I mean it's not on the DB level is it? I can see why it would be useful, but it's really about validation, not referential integrity.

  16. Joshua Haberman2007-07-15 17:40:59

    I was intrigued to discover about six months ago that databases can enforce constraints in a way that is actually impossible from client code.

    Say you have tables a and b:


    Now say you have two concurrent connections. The first connection says:

    SQL> INSERT INTO a (id) VALUES (1); SQL> BEGIN; SQL> DELETE FROM a; (note: this transaction is uncommitted)

    Now the second connection says:

    SQL> INSERT INTO b (id, a_id) VALUES (1, 1);

    What now? Should this command on connection two succeed or fail? The correct answer is: we don't know until connection one commits or rolls back. If you let it succeed, but connection one commits, the database will be inconsistent. It is impossible for your client code to detect this condition, because "SELECT id FROM a WHERE id=1" will continue to return that row in a, even though it has been deleted in a concurrent transaction.

    A properly MVCC database will make the second connection's INSERT block until the first connection either commits or rolls back. Only then does it know whether the operation should succeed or fail.

    Given this, I would really urge you to leave constraints to DBMS's. It is impossible to truly guarantee integrity otherwise.

  17. Ryan Norbauer2007-07-15 21:42:32

    Thanks Josh! This has been a long time coming, particularly because people get confused about the functioning of "validates_associated" and assume that it does what your plugin does. Bravo.

    I hope this validation finds its way into core.

  18. Joshua Haberman2007-07-16 16:49:52

    I've been thinking about this problem a lot in the last day. I thought of some ways, using row-level locks (SELECT FOR UPDATE), to get around some of the initial problems I mentioned, but then other problems would pop up.

    As a Rails user and advocate, I beg you: please don't sell this as an alternative to foreign keys in a database. It cannot guarantee consistency the way that foreign keys can. It will be possible to insert data that does not follow the rules of your "validatesexistenceof" constraint. I gave one example above of how this could happen.

  19. Josh Susser2007-07-16 17:32:25

    Joshua Haberman: I agree with what you have to say. This validation is not a replacement for referential integrity checking through foreign key constraints in the DB. If you don't need foreign key constraints, this validation can help you by providing some consistency at the model level. And if you are going to use foreign key constraints, this should be helpful by enabling you to provide a valid? test that is meaningful.

    Personally, I haven't run into a situation where I've really needed foreign key constraints in the DB. Using ActiveRecord model classes (with validations) for all updates to the DB keeps me from doing something stupid to the DB. validates_existence_of gives me another tool to help me out there.

  20. CM Harrington2007-07-16 20:23:15

    I think this is really cool, but it seems to miss the point of having referential integrity in the DB in the first place. Most companies have more than one app talking to the database. It kinda messes up the DRY idea as you're now saying every app is supposed to create a referential integrity model, when it could be consolidated in the database. This also makes tweaks to the DB's model have to cascade to all the applications' RI model.

  21. Josh Susser2007-07-16 22:17:20

    CM: Welcome to Rails! DHH says Rails is built to work with an "application db", not an "integration db". In short, you should only have one app talking to a db. DHH views a db as a big hash table in the sky (with joins). Your concerns make sense in general, but in the world of Rails they usually don't apply.

  22. JCL2007-07-17 09:51:44

    Execellent work!!! I for one would love to see this go into core.

    Offtopic slightly, I never really figured out why someone would use validates_associated? I have always thought if the associated record was inserted through its own rails model, it must have already passed validation in that model.

  23. Matt Aimonetti2007-07-18 22:24:44

    Good stuff Josh, I decided to use your plugin to keep my model simpler while being fully validated :) if you didn't do it yet, I would really encourage you to submit a patch.

  24. Bosko2007-07-26 21:25:47

    Have you submitted this? I really think this should be part of core. I've been wanting this behavior for some time and have had my own implementation rolled up in local svn. Now that I've seen yours, I think it is certainly core-worthy.

  25. cbmeeks2007-07-28 03:18:42

    I'm sorry, but I just can't get on board with the whole "trust rails, ditch referential integrity in the db".

    My first instinct as a db admin and C# developer is to setup proper referential integrity at the db level. I live in a small town where most developers never even heard of rails (at least not in corporate) and if I walked in and mentioned an idea of dropping foreign keys they would laugh me out of town...even if they are right or wrong.

    now at work, I am helping on a large C# Windows app that helps in budgeting for the entire company. some very complex joins from 4-6 tables or more. A nightmare to the "keep it simple" crowd. I read a lot of how joins are stupid, de-normalize, etc. That is fine until you need information on literally 30 topics per row.

    Anyway, I am drifting in and out of sleep. Point is, the database layer of an application should be framework agnostic. Maybe that's not the whole idea of Rails and I really love Rails as I am learning it, I just don't get it.

    I LIKE that extra security and it makes me sleep better at night knowing that the goobers that use my apps have one less way to f@%k things up. Sure, they will find another way but still.

    Anyway, I'm going to see what I can do about my app and keeping foreign key constraints. My need are really simple at the moment so hopefully I will find a slick way to handle it.


  26. Josh Susser2007-07-28 18:51:06

    cbmeeks: If you want to do fk constraints in the db, have at it. The Rails approach often pisses off DBAs, as it essentially considers a db as a big hash table for storing objects. Eventually someone will build an object database that works with Ruby/Rails and we won't have to have these conversations anymore.

  27. nachokb2007-08-02 16:59:09

    Candidate for core!

  28. Senthil Nayagam2007-08-18 05:19:19

    Hi John,

    I was plagued by orphaned data as I had extensively used Polymorphic Associations.

    it works on 1.1.6 as well and it saved my day

  29. Ruby on Rails lover2007-08-21 10:49:14

    Works very well on 1.2.3

  30. benanne2007-08-31 12:02:56

    Exactly what I was looking for! I hope it makes it into core :)

Sorry, comments for this article are closed.