【问题标题】:Rails - omit model name from nested validation error messagesRails - 从嵌套验证错误消息中省略模型名称
【发布时间】:2016-02-18 16:08:48
【问题描述】:

在我的item 模型中,当item 得到验证时,我有has_many :user_items, validate: true 行来验证关联的user_item 模型。验证错误消息如下所示:

>>  @item.errors
=> ... @messages={:name=>["can't be blank"],
                  :description=>["can't be blank"],
                  :"user_items.picture"=>["can't be blank"], 
                  :user_items=>["is invalid"]}>
>>  @item.errors.full_messages
=> ["Name can't be blank",
    "Description can't be blank", 
    "User items picture can't be blank",
    "User items is invalid"]

_error_messages.html.erb

<% if target.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(target.errors.count, "error") %>.
    </div>
    <ul>
    <% target.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

项目的错误消息不显示项目名称。例如,错误消息不显示“项目描述不能为空白”,它只显示“描述不能为空白”。如何使用户项的错误消息以相同的方式省略模型名称,例如“图片不能为空白”而不是“用户项的图片不能为空白”?

【问题讨论】:

    标签: ruby-on-rails validation activerecord


    【解决方案1】:

    您可以为此使用 ActiveRecord 的内置 I18n 实现。更新您的config/locales/en.yml 如下:

    en:
      activerecord:
        attributes:
          item/user_items:
            picture: 'Picture'
    

    这将确保您对user_items.picuture 的验证消息显示属性名称的“图片”而不是“用户项目图片”。

    更多详情请参阅"Translations for Active Record Models"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2014-09-26
      • 2015-12-28
      相关资源
      最近更新 更多