Rails - validates_uniqueness_of: access duplicate item?
I have a basic Rails model with two properties, name and code. I have validates_uniqueness_of for the code property. However, I'd like to customize the :message to show the name of the duplicate. Is there any way to access this duplicate item?
For example, say I first enter a record called Expired with code EXP. Then I enter开发者_StackOverflow Experience with code EXP. I would like the :message to say something like "Code already taken by Expired".
> m1 = Model.new(:name => 'Expired', :code => 'EXP')
> m2 = Model.new(:name => 'Experience', :code => 'EXP')
> m1.save!
> m2.save!
validates_uniqueness_of :code,
:message => "Code already taken by #{duplicate.name}"
Is there any built-in Rails construct that holds the duplicate object so that I can access it like I do in the :message? Or is there any other way I can run code to determine the duplicate when this validation gets triggered?
I believe you'd have to write a custom validation method. Something like:
def validate
model = Model.first(:conditions => {:code => self.code})
unless model.blank? && (self.id != model.id)
errors.add_to_base "Code already taken by #{model.name}"
end
end
As per @j but as a validation callback and target the message specifically to the failing attribute
validate do |model|
duplicate = Model.first(:conditions => {:code => model.code})
if duplicate
model.errors.add :code, "already taken"
end
end
精彩评论