istrasci
istrasci

Reputation: 1351

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 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?

Upvotes: 3

Views: 385

Answers (2)

Ju Nogueira
Ju Nogueira

Reputation: 8461

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

Upvotes: 3

bjg
bjg

Reputation: 7477

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

Upvotes: 2

Related Questions