这是一个我需要帮助的奇怪问题。
所以我正在尝试验证表单中的复选框,以便至少选择一个:
...
<div class="form-group">
<%= f.collection_check_boxes(:topping_ids, Topping.all, :id, :name, include_hidden: false) do |b| %>
<ul>
<li><%= b.check_box %> - <%= b.label %></li>
</ul>
</div>
...
我的模特:
class Pizza < ApplicationRecord
has_many :pizza_toppings, dependent: :destroy
has_many :toppings, through: :pizza_toppings
validates_presence_of :name
validates_length_of :topping_ids, minimum: 1, message: "You must select at least 1 topping"
end
我的错误部分:
<% if object.errors.any? %>
<div id="error_explanation">
<div class="errors-alert text-center">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li class="errors-alert-item text-center"><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
这就是错误:
如何在错误中更改或删除“Topping id”。我学会了如何更改消息,但我不确定我会为“Toppings id”改变什么,它显然对用户没用。我不想从本地或类似的东西更改错误,因为我使用了其他表单的验证,所以我希望能够看到这些错误,这是我唯一需要修改的错误。
答案 0 :(得分:1)
将区域设置用于自定义错误消息。
# config/locales/en.yml
en:
activerecord:
attributes:
pizza:
topping_ids: ""
您需要覆盖属性名称。
但请记住,使用
时,属性名称不会显示在任何位置errors.full_messages
或者使用errors.messages
代替errors.full_messages
答案 1 :(得分:0)
您可以改用<% object.errors.values.flatten.each do |msg| %>
。
答案 2 :(得分:0)
或试试这个:
<% object.errors.full_messages.each do |attr,msg| %>
<li class="errors-alert-item text-center"><%= msg %></li>
<% end %>
如果你改为:
<%= attr %> <%= msg %>
您收到带有属性名称
的错误消息