【问题标题】:errors.full_messages: attribute name appears twiceerrors.full_messages:属性名称出现两次
【发布时间】:2011-01-25 09:56:38
【问题描述】:

这一直困扰着我一段时间。我的所有模型都会出现这个问题,但我将使用其中一个,测验,作为示例。

测验具有以下验证:

validates_presence_of :size, :style

我使用的是 I18n,我的翻译文件中有以下设置:(这些只是标准错误消息,但我已将它们包含在我的 en.yml 中,以便于查看结构,如果我想为任何特定型号覆盖它们)

activerecord:
  errors:
    messages:
      inclusion: "{{attribute}} is not included in the list"
      invalid: "{{attribute}} is invalid"
      empty: "{{attribute}} can't be empty"
      blank: "{{attribute}} can't be blank"
      record_invalid: "Validation failed: {{errors}}"   

问题是这样的:如果我做一个新的测验,验证将失败,然后查看 quiz.errors.full_messages,每个错误消息都有属性,然后是完整消息:

>> quiz = Quiz.create
=> <unsaved quiz object>
>> quiz.errors.full_messages
=> ["Size Size can't be blank", "Style Style can't be blank"]

我不明白为什么消息是 "Size Size can't be blank" 而不是 "Size can't be blank"

有什么想法吗?

【问题讨论】:

  • 是否有任何特殊原因需要在每条验证消息中添加{{attribute}}?通常,那里的条目将仅包含错误消息,例如“未包含在列表中”。该属性将根据您的语言环境文件中的activerecord.errors.full_messages.format 自动添加,默认为"%{attribute} %{message}"
  • 嗨,西卡丘。这就是他们在供应商轨道中的方式 - 我只是将该文件的内容复制到我的 en.yml 文件中(已注释掉),然后取消注释并根据需要进行修改。

标签: ruby-on-rails validation activerecord


【解决方案1】:

应该还有:

en:
  errors:
    # The default format to use in full error messages.
    format: "%{attribute} %{message}"

您的其他翻译不应再包含%{attribute}。 为了确保您从 Rails 版本中正确使用 en.yml, 它位于:lib/ruby/gems/1.8/gems/activemodel-3.0.3/lib/active_model/locale/en.yml

【讨论】:

  • 感谢 Gertas,这也是我想出来的,虽然我的基础是供应商 rails 而不是 activemodel 3(我使用的是 rails 2.3.4)
【解决方案2】:

我只是想通了这一点,并想我会自己回答,以防其他人遇到这个问题:我不得不修改我的翻译文件的 activerecord 部分:

activerecord:
  errors:
    full_messages:
      format: "{{message}}"    
    #define standard error messages, which we can overide on per model/per attribute basis further down
    messages:
      inclusion: "{{attribute}} is not included in the list"
      exclusion: "{{attribute}} is reserved"

问题在于activerecord.errors.full_messages.format 键被设置(在vendor/rails/activerecord/lib/active_record/locale/en.yml 中)为“{{attribute}} {{message}}”,而消息又被设置为“{{attribute}} can' t 是空白的”例如。所以 full_message 以“{{attribute}} {{attribute}} 不能为空”的形式出现。将其更改为“{{message}}”即可解决此问题。

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多