Validates_uniqueness_of: access to duplicate element?

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?

+3
source share
2 answers

I believe that you will have to write a special verification method. Sort of:

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
+3
source

According to @j, but as a validation callback and target message specifically for fail attribute

validate do |model|
   duplicate = Model.first(:conditions => {:code => model.code})
   if duplicate
     model.errors.add :code, "already taken"
   end
end
+2
source

Source: https://habr.com/ru/post/1752689/


All Articles