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

Jas*_*ett 9 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.
Run Code Online (Sandbox Code Playgroud)

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

start_time_time
start_time_time
start_time_ymd
start_time_ymd
stylist_services
Run Code Online (Sandbox Code Playgroud)

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

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

Ken*_*enB 24

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

en:
  errors:
    format: "%{message}"
Run Code Online (Sandbox Code Playgroud)

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


Mic*_*ley 21

循环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>
Run Code Online (Sandbox Code Playgroud)

但是"完整"消息包含本地化的字段名称后跟消息(正如您所见;这是因为消息通常是"不能为空").如果您只想要实际的错误消息减去字段名称,请使用内置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>
Run Code Online (Sandbox Code Playgroud)


Zab*_*bba 17

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

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

en:
  activerecord:
    attributes:
      somemodel:
        start_time_time: My Start Time Text  #renamed text
        stylist_services: "" #hidden txet
Run Code Online (Sandbox Code Playgroud)