Search code examples
ruby-on-railsvalidation

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?


Solution

  • Try something like this

    validate :uniqueness_of_name
    
    def uniqueness_of_name
       existing_record = Model.find_by_name(name)
       unless existing_record.nil?
         errors.add(:name, "Record #{existing_record.id} already has the name #{name}")
       end
    end