Rails 4 custom message validate_uniqueness
I originally thought you could solve this by writing a custom validator like:
class NameValidator
def validate record
unless record.name.include? 'somestring'
record.errors[:name] << "#{record.name} is not valid"
end
end
end
However, I don't think it can be accessed record
as in the example above.
validate_uniqueness_of
doesn't give you access to a single entry until pretty far down the stack. Eventually, the code jumps to validate_each
, after which you access the individual record. Therefore, you need to implement your ownvalidate_each
or extend your existing one .
It looks like there is a default way to do this in Rails. Of course, I would be interested to know if there is a better way :)
source to share
@Usha uniqueness confirmation code will not work correctly when updating an existing record because it Model.find_by_name(name)
returns the updated record.
validate :uniqueness_of_name
def uniqueness_of_name(current_record)
existing_record = Model.find_by_name(name)
unless existing_record.nil? || existing_record.id == current_record.id
errors.add(:name, "Record #{existing_record.id} already has the name #{name}")
end
end
source to share