I have a basic Rails model with two properties, name and code. I have a validates_uniqueness_of property for a code property. However, I would like to customize the message: to show the name of the duplicate. Is there a way to access this duplicate element?
For example, let's say I first entered an entry called Expired with the code EXP . Then enter Experience with EXP code . I would like the message: "Something like" Code already accepted 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 a built-in Rails construct that contains a duplicate object so that I can access it, as in the message :? Or is there another way I can run the code to determine the duplicate when this check fires?
source
share