0

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:

snapshot

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.

1
  • you have to provide the name alternative in the locals file for the specific attribute. Commented Aug 4, 2016 at 15:53

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Changing the specific attribute in the locales works perfectly for what I needed! Thanks!
0

You could use <% object.errors.values.flatten.each do |msg| %> instead.

Comments

0

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

1 Comment

ah that would work but I have the error code in a partial that I want to use for multiple forms to keep my code DRY. I need the <%= attr %> for other validations and forms so I can't completely remove it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.