Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 273
user4584963 Avatar asked Jan 26 '26 18:01

user4584963


1 Answers

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.

like image 141
vee Avatar answered Jan 28 '26 16:01

vee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!