Dave Dave - 4 months ago 7
Ruby Question

In RoR, how do I customize a validation error message that is set to numericality greater than zero?

I’m using Rails 4.2.7. I have this validation rule for my model

class MyObjectTime < ActiveRecord::Base

validates :time_in_ms, numericality: { greater_than: 0 }


I want to write a custom error message, so in my config/locales/en.yml file I included

en:
activerecord:
attributes:
my_object:
name: "Name"
my_object_time:
time_in_ms: "Time"
errors:
models:
my_object_time:
attributes:
time_in_ms:
not_a_number: "This field must be a number greater than zero."
blank: "This field must be a number greater than zero."


But when my object fails to validate, this custom error message is not included in my @my_object_time.errors.full_messages array . Instead what is included is

Must be greater than 0


What is the proper rule to write in my config file so that I can customize this error message?

Answer

You can customize message directly in model.

class MyObjectTime < ActiveRecord::Base

  validates :time_in_ms, numericality: { greater_than: 0 }, message: 'my customized message.'

end

or in your en.yml file you need to add message for greater_than:

en:
  activerecord:
    attributes:
      my_object:
        name: "Name"
      my_object_time:
        time_in_ms: "Time"
    errors:
      models:
        my_object_time:
          attributes:
            time_in_ms:
              not_a_number: "This field must be a number greater than zero."
              blank: "This field must be a number greater than zero."
              greater_than: "my custom message for greater than"
Comments