【问题标题】:How do I localize custom error messages in rails active record validations?如何本地化 Rails 活动记录验证中的自定义错误消息?
【发布时间】:2018-11-14 22:19:24
【问题描述】:

具体来说,我试图本地化 自定义方法 示例 here。我发现了一个类似的question,但我不知道如何在 errors.add() 方法中传递那个 :message 参数。我试着做这样的事情:

errors.add(:discount, message: :greater_than_value_error)

但它会打印:

{:message=>:greater_than_value_error} 

而不是打印 .yml 文件中的实际错误消息。

这里的正确语法应该是什么?

我的 .yml 文件看起来像这样(不确定下面这段是否 100% 准确):

activerecord: #try to use activemodel here
  errors:
    models:
      invoice: # or namespace/model_name
        attributes:
          discount:
            greater_than_value_error: "can't be greater than total value"

【问题讨论】:

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


    【解决方案1】:

    尝试使用 rails 4 关注 errors.add :field_name, :message

    errors.add(:discount, :greater_than_value_error)
    

    【讨论】:

      【解决方案2】:

      如果您正在编写自定义验证,那么您需要进行实际翻译,

      errors.add(:discount, I18n.t(path_to_locale_text))
      

      仅当您使用内置方法时,您才能将标准验证消息国际化,例如预定义验证器 greater_than_value_error

      validates_numericality_of :discount :greater_than => limit
      

      查看https://stackoverflow.com/a/4453350/1232447了解更多详情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多