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

时间:2011-04-03 00:25:09

标签: ruby-on-rails ruby-on-rails-3

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

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

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

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

4 个答案:

答案 0 :(得分:24)

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

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

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

答案 1 :(得分:20)

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

<% 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>

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

<% 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>

答案 2 :(得分:17)

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

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

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

答案 3 :(得分:0)

我做的几乎和布兰登一样。

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

#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

然后,在具有验证形式的视图中,我做了: (注意:这是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)

这对我来说,没有宝石或第三方插件。

-Demitry