0

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?

Dave
  • 15,639
  • 133
  • 442
  • 830
  • Possible duplicate of [Fully custom validation error message with Rails](http://stackoverflow.com/questions/808547/fully-custom-validation-error-message-with-rails) – danilopopeye Aug 01 '16 at 20:09

1 Answers1

1

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"
r3b00t
  • 6,953
  • 6
  • 27
  • 37