Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 custom validate_uniqueness message

Is it possible that in the error message of validate_uniqueness_of to show the id of the record that already has the field that i'm checking the uniqueness?

like image 329
user3477834 Avatar asked Sep 18 '14 16:09

user3477834


2 Answers

@vimsha's solution may work but I found a way neater way that allows to still use validates_uniqueness_of rather than creating your own validator:

validates_uniqueness_of :identifier, message: lambda{|x, y| "#{MyModel.find_by_identifier(y[:value]).id} is already taken" }
like image 182
edwardmp Avatar answered Sep 29 '22 14:09

edwardmp


@usha's uniqueness validation code will incorrectly fail when updating an existing record since Model.find_by_name(name) returns the record being updated.

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
like image 44
Tim Raasveld Avatar answered Sep 29 '22 15:09

Tim Raasveld