设计 activerecord 错误自定义消息及其翻译

Devise activerecord errors custom messages and its translation

我正在尝试自定义 activerecords 错误消息。这是我拥有的:

我的错误信息部分文件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 %>

我的 YML 文件:

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

但显示的错误消息包含更多内容。它显示:

电子邮件等等等等

这是为什么?为什么它在翻译的开头显示 'Email' 个单词,以及如何在不创建我自己的验证的情况下删除这个额外的 'Email' 字符串?

这是我在阅读 Whosebug 上连接的所有内容时发现的内容:

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}").

但我不知道如何格式化我的 YML 文件。请支持

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

适用于我的情况

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

这就是 full_messages 方法默认的工作方式(默认格式为 "%{attribute} %{message}")。

您可以使用以下任何 I18n 键更改它:

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

查看文档以获取更多信息:https://apidock.com/rails/v6.0.0/ActiveModel/Errors/full_message

编辑:你的 yml 文件中有这样的内容:

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