views:

18

answers:

1

I have Labellings which belong to Emails and Labels.

Each labelling must be unique to the email/label pair - so an email can only be labelled 'test' once.

I'm doing this with validates_uniqueness_of :label_id, :scope => :email_id. This works as expected.

When I am labelling emails, I want to add the labelling if it is unique, and do nothing if the email is already labelled with that label.

I don't want to duplicate the validation functionality around my app with something like:

email.labels << label unless email.labels.include?(label)

Is it possible to ensure each labelling has a unique email_id/label_id pair without having to check it manually or handle exceptions?

+1  A: 

I haven't tested it, but you can probably override << in the association proxy, something like:

class Email < ActiveRecord::Base
  has_many :labelings
  has_many :labels, :through => :labelings do
    def <<(label)
      unless proxy_owner.labels.include?(label)
        proxy_owner.labelings << Labeling.new(:email => proxy_owner, :label => label)      
      end
    end
  end

end
pjb3
Fantastic - works a treat! Also taught me some new tips about ActiveRecord :)
nfm