I created a callback when creating a new Client object instead of using the validates_uniqueness_of validation method because:
- I want to find the Client that already exists
- Add the existing Client details to my base error message
My question: is there a more elegant way of achieving this than my solution below?
I have the following model:
class Client < ActiveRecord::Base
before_validation_on_create :prevent_duplicate_clients
private
def prevent_duplicate_clients
client = self.class.find(:all, :conditions => ["first_name = ? AND middle_name = ? AND last_name = ? AND date_of_birth = ?", self.first_name, self.middle_name, self.last_name, self.date_of_birth])
if client.size >= 1
self.errors.add(:base, "Client exists as #{client.first.name}")
false
end
end
end
NB:
- Rails v2.3.5
You shouldn’t put validation code in the before_validation callbacks. Change
before_validation_on_create :prevent_duplicate_clientstovalidate :prevent_duplicate_clients