Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error messages always include attribute name

I have the following validation error messages coming up when I try to submit a blank form:

Start time time Looks like you forgot the appointment start time.
Start time time Sorry, we can't understand "" as a time.
Start time ymd Please choose a date for the appointment.
Start time ymd Sorry, we can't understand "" as a date.
Stylist services Please choose at least one service.

These messages are for the following attributes:

start_time_time
start_time_time
start_time_ymd
start_time_ymd
stylist_services

I included the attribute names so you could plainly see which part of the error message is the attribute name.

How do I remove the attribute names from the error messages?

like image 772
Jason Swett Avatar asked Apr 03 '11 00:04

Jason Swett


2 Answers

You could use the i18n route to change the display name of the attribute.

config/locales/en.yml:

en:
  activerecord:
    attributes:
      somemodel:
        start_time_time: My Start Time Text  #renamed text
        stylist_services: "" #hidden txet
like image 170
Zabba Avatar answered Oct 04 '22 08:10

Zabba


It's common to loop over object.full_messages to output each full message:

<% if object.errors.any? %>
  <h2>Errors</h2>
  <ul>
  <% object.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
<% end %>

<h2>Errors</h2>
<ul>
  <li>Start time time Looks like you forgot the appointment start time.</li>
  <li>Start time time Sorry, we can't understand "" as a time.</li>
  <li>Start time ymd Please choose a date for the appointment.</li>
  <li>Start time ymd Sorry, we can't understand "" as a date.</li>
  <li>Stylist services Please choose at least one service.</li>
</ul>

But a "full" message consists of the localized field name followed by the message (as you've seen; this is because the messages are usually things like "can't be blank"). If you just want the actual error message minus the field name, use the built-in each iterator instead:

<% if object.errors.any? %>
  <h2>Errors</h2>
  <ul>
  <% object.errors.each do |field, msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
<% end %>

<h2>Errors</h2>
<ul>
  <li>Looks like you forgot the appointment start time.</li>
  <li>Sorry, we can't understand "" as a time.</li>
  <li>Please choose a date for the appointment.</li>
  <li>Sorry, we can't understand "" as a date.</li>
  <li>Please choose at least one service.</li>
</ul>
like image 31
Michelle Tilley Avatar answered Oct 04 '22 06:10

Michelle Tilley