Rails 4 custom message validate_uniqueness

Is it possible that the validate_uniqueness_of error message will show the id of a record that already has a field that I am checking for uniqueness?

+3


source to share


4 answers


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

      

+1


source


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 :)

0


source


@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

      

0


source


@ Vimsha's solution might work, but I found a way in a neater way that allows you to use validates_uniqueness_of

instead of creating your own validator:

validates_uniqueness_of :identifier, message: lambda{|x, y| "#{MyModel.find_by_identifier(y[:value]).id} is already taken" }

0


source







All Articles