在 RoR 中,如何自定义设置为大于零的数值的验证错误消息?

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

我正在使用 Rails 4.2.7。我的模型有这个验证规则

class MyObjectTime < ActiveRecord::Base

  validates :time_in_ms, numericality: { greater_than: 0 }

我想编写自定义错误消息,因此在我的 config/locales/en.yml 文件中包含了

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."

但是当我的对象验证失败时,这个自定义错误消息不包含在我的@my_object_time.errors.full_messages 数组中。相反,包含的是

Must be greater than 0

在我的配置文件中写入什么正确规则以便我可以自定义此错误消息?

您可以直接在模型中自定义消息。

class MyObjectTime < ActiveRecord::Base

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

end

或者在您的 en.yml 文件中,您需要为 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"