首页 > 解决方案 > 在关联错误消息中隐藏/删除模型名称

问题描述

对于我的一生,我找不到如何在错误消息之前删除“型号名称”。通常这没关系,但请听我说完。

我有一个名为“foo”的模型。我需要在某个时候重命名它,但现在它很麻烦。现在,我需要更改错误消息:“Foo 你获得报酬的频率缺失”。

# finance.rb
belongs_to :foo # this will be renamed in the future
[..]

我以为我只需要编辑 en.yml :

en:
  activerecord:
    errors:
      models:
        finance:
          attributes:
            foo:
              required: "How often you get paid is missing"

这可行,但我不需要在消息中显示模型的名称。好的,我可以做一些字符串替换,但这很难看。是否可以仅在 中显示消息en.yml

编辑:

错误显示为:

<% if @finance.errors.any? %>
  <ul>
    <% @finance.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
  </ul>
<% end %>

标签: ruby-on-railsruby-on-rails-6

解决方案


似乎是在这里找到的一个简单的解决方案。所以在我的情况下:

en:
  errors:
    format: "%{message}"
  activerecord:
    errors:
      models:
        finance:
          attributes:
            repayment_type:
              required: "How often you get paid is missing"

这可能是重复的帖子,因此您可以标记为重复


推荐阅读