简体   繁体   中英

Rails - omit model name from nested validation error messages

In my item model I have the line has_many :user_items, validate: true to validate the associated user_item model when item gets validated. Validation error messages look like this:

>>  @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 %>

Error messages for item does not show the item name. For example the error message does not show "Item description can't be blank" it just shows "Description can't be blank." How can I make it so the error messages for user items omit the model name the same way for example "Picture can't be blank" instead of "User items picture can't be blank"?

You can use ActiveRecord's built-in I18n implementation for this. Update your config/locales/en.yml as follows:

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

This will ensure that your validation message for user_items.picuture shows 'Picture' instead of 'User items picture' for the attribute name.

See "Translations for Active Record Models" for further details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM