Ignoring specific validation errors
-
21-09-2019 - |
Question
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?
Solution
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow