How to handle this type of model validation in Ruby on Rails

Posted by randombits on Stack Overflow See other posts from Stack Overflow or by randombits
Published on 2010-04-18T16:24:37Z Indexed on 2010/04/18 16:33 UTC
Read the original article Hit count: 231

Filed under:
|

I have a controller/model hypothetically named Pets. Pets has the following declarations:

:belongs_to owner
:has_many dogs
:has_many cats

Not the best example, but again, it demonstrates what I'm trying to solve. Now when a request comes in as an HTTP POST to http://127.0.0.1/pets, I want to create an instance of Pets. The restriction here is, if the user doesn't submit at least one dog or one cat, it should fail validation. It can have both, but it can't be missing both.

How does one handle this in Ruby on Rails? Dogs don't care if cats exists and the inverse is also true. Can anyone show some example code of what the Pets model would look like to ensure that one or the other exists, or fail otherwise?

errors.add also takes an attribute, in this case, there is no particular attribute that's failing. It's almost a 'virtual' combination that's missing.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord