【问题标题】:Rails i18n specific error validation formatsRails i18n 特定的错误验证格式
【发布时间】:2012-09-22 10:05:31
【问题描述】:

因此,您可以使用以下内容更改 en.yml 中的错误消息:

en:
  activerecord:
    errors:
      models:
        foo:
          attributes:
            amount:
              greater_than_or_equal_to: "Custom GTOE error message."

但是,这将说明以下内容:

Amount Custom GTOE error message.

我知道我可以通过以下方式全局删除它:

en:
  activerecord:
    errors:
      format: "%{message}"

但我可以删除%{attribute} 仅用于此验证吗?

谢谢!

【问题讨论】:

  • 见github.com/rails/rails/pull/7369,但仍然打开
  • 文档说“它们都接受 :on 和 :message 选项,它们分别定义了何时应该运行验证,以及如果验证失败,应该将什么消息添加到错误集合中。”所以我认为你应该在验证参数中使用message: I18n.t('custom.error_message')。但这只是一个随机猜测,我从未使用过这种方式。

标签: ruby-on-rails ruby validation activerecord internationalization


【解决方案1】:
 validates :amount, :numericality => { :greater_than_or_equal_to => YOUR_VALUE, :message => YOUR_ERROR_MESSAGE }

【讨论】:

  • 不正确!仍然会有“%{attribute} YOUR_ERROR_MESSAGE”
  • 不正确,正如安德鲁所说,它仍然具有属性
【解决方案2】:

我不确定你是否可以将它从 en.yml 中删除,但你可以制作一个我认为会有你想要的签名的自定义:

def discount_cannot_be_greater_than_total_value
    if attribute > total_value
      errors.add(:base, "can't be greater than total value")
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    相关资源
    最近更新 更多