错误消息始终包含属性名称

当我尝试提交空白表单时,我会收到以下validation错误消息:

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. 

这些消息适用于以下属性:

 start_time_time start_time_time start_time_ymd start_time_ymd stylist_services 

我包含了属性名称,因此您可以清楚地看到错误消息的哪一部分是属性名称。

如何从错误消息中删除属性名称?

您可以使用i18n路由更改属性的显示名称。

配置/区域设置/ en.yml:

 en: activerecord: attributes: somemodel: start_time_time: My Start Time Text #renamed text stylist_services: "" #hidden txet 

在rails 3.2.6中,您可以通过在语言环境文件中设置errors.format来抑制包含属性名称(例如,config / locales / en.yml):

 en: errors: format: "%{message}" 

否则,默认格式为“%{attribute}%{message}”。

循环遍历object.full_messages以输出每个完整的消息是很常见的:

 <% if object.errors.any? %> 

Errors

    <% object.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %>

Errors

  • 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.

但是“完整”消息包含本地化的字段名称后跟消息(正如您所见;这是因为消息通常是“不能为空”)。 如果您只想要实际的错误消息减去字段名称,请使用内置的each迭代器:

 <% if object.errors.any? %> 

Errors

    <% object.errors.each do |field, msg| %>
  • <%= msg %>
  • <% end %>
<% end %>

Errors

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

我和布兰登几乎做了同样的事情。

首先,我为错误将呈现的对象编写了一个辅助函数。

 #Remove unnecessary attribute names in error messages def exclude_att(attribute, error_msg) if attribute.to_s == "Put attribute name you don't want to see here" error_msg else attribute.to_s.humanize + " " + error_msg end end 

然后,在具有validationforms的视图中,我做了:(注意:这是HAML代码而不是HTML,但标签仍然相同,因此您可以清楚地看到我在做什么)

 %h3= "#{pluralize(@user.errors.count, 'error')} prohibited this user from being saved:" %ul - @user.errors.each do |att, error| %li= exclude_att(att, error) 

这样做对我来说,没有gem或第三方插件。

-Demitry