Rails valiation among a three model relationship

Posted by Andrew on Stack Overflow See other posts from Stack Overflow or by Andrew
Published on 2012-11-12T04:57:33Z Indexed on 2012/11/12 4:59 UTC
Read the original article Hit count: 116

I'm working on a three model relationship with one aspect that I'm not sure how to approach. Here's the basic relationship:

class Taxonomy
  has_many :terms
  # attribute: `inclusive`, default => false
end

class Term
  belongs_to :taxonomy
  has_and_belongs_to_many :photos
end

class Photo
  has_and_belongs_to_many :terms
end

This is pretty straightforward stuff except for one thing:

A Taxonomy can be either 'Inclusive' or 'Exclusive'. Exclusive means the terms are mutually exclusive, Inclusive means they're not.

So, if a Taxonomy is exclusive ie. taxonomy.inclusive = false, then there can only be one term from that taxonomy attached to a given photo.

Now, I can handle this on the client-side without a problem, but I am not quite sure how to set up a validation on Photos (or somewhere else) that says basically: "validate that no more than one term from an exclusive taxonomy is associated with this record."

Any ideas on how to do that?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord