Mick Lasocki
Mick Lasocki

Reputation: 139

Devise activerecord errors custom messages and its translation

I'm trying to customize activerecords error messages. Here is what I have:

my error message partial file app/views/devise/shared/_error_messages.html.erb:

<% if resource.errors.any? %>
  <div id="error_explanation" class="verd14 pl-2 pr-2">
      <%= I18n.t("errors.messages.not_saved",
                 count: resource.errors.count,
                 resource: resource.class.model_name.human.downcase)
       %>
    <ul>
      <% resource.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
    </ul>
  </div>
<% end %>

my YML file:

pl:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              blank: "blah blah blah"

But the presented error message contains something more. It shows:

Email blah blah blah

Why is that? Why does it show 'Email' word at the beginning of the translation and what to do to get rid of this additional 'Email' string without creating my own validations?

here is what I found reading everything connected on stackoverflow:

ActiveModel::Errors#full_messages prepends the attribute name to the error message using a separator that will be looked up from errors.format (and which defaults to "%{attribute} %{message}").

but I don't know how to format my YML file. Please support

Upvotes: 2

Views: 839

Answers (2)

arieljuod
arieljuod

Reputation: 15848

"Why is that? Why does it show 'Email' word at the beginning of the translation"

That's how the full_messages method work by default (default format is "%{attribute} %{message}").

You can change that with any of this I18n keys:

activemodel.errors.models.user.attributes.email.format
activemodel.errors.models.user.format
errors.format

Check the docs for more information: https://apidock.com/rails/v6.0.0/ActiveModel/Errors/full_message

EDIT: something like this on your yml file:

pt:
  activemodel:
    errors:
      user:
        attributes:
          email:
            blank: 'bla bla bla'
            format: '%{message}'

Upvotes: 2

Mick Lasocki
Mick Lasocki

Reputation: 139

<% resource.errors.values.each do |message| %>
        <li><%= message[0] %></li>

works in my case

Upvotes: 0

Related Questions