Reputation: 511
Here's a strange problem I needed help with.
So I'm trying to validate the checkboxes in my form so that atleast one has to be selected:
...
<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>
...
My Model:
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
My error partial:
<% 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 %>
This is what the error looks like:
How do I change or get rid of that "Topping ids" in the error. I learned how to change the message but I'm not sure what I would change for "Toppings ids", it obviously provides no use to the user. I don't want to change the error complete from locals or anything like that because I used validations for other forms so I want to be able to see those errors, this is the only one I need to modify for.
Upvotes: 0
Views: 129
Reputation: 3685
Or try this:
<% object.errors.full_messages.each do |attr,msg| %>
<li class="errors-alert-item text-center"><%= msg %></li>
<% end %>
If you do instead:
<%= attr %> <%= msg %>
you get this error message with the attribute name
Upvotes: 0
Reputation: 2049
You could use <% object.errors.values.flatten.each do |msg| %>
instead.
Upvotes: 0
Reputation: 23711
Use locales for custom error messages.
# config/locales/en.yml
en:
activerecord:
attributes:
pizza:
topping_ids: ""
You will need to override the attribute name.
But remember the attribute name will not be displayed anywhere when you use
errors.full_messages
Or go with errors.messages
instead of errors.full_messages
Upvotes: 1