如何在Rails中更改“3个错误禁止此foobar被保存”validation消息?

在我的rails应用程序中,我在我的活动记录对象中使用validation助手,它们非常棒。 当出现问题时,我会在我的网页上看到标准的“3个错误禁止这个foobar被保存”以及个别问题。

有什么办法可以用我自己的方式覆盖这个默认消息吗?

用于显示错误的error_messages_for帮助程序接受:header_message选项,允许您更改该默认标题文本。 如:

error_messages_for 'model', :header_message => "You have some errors that prevented saving this model"

RubyOnRails API是你的朋友。

模型中的“validates_”方法通常都可以传递给:message =>“我的validation消息”参数。

我通常将错误包装在这样的事情中:

 <% if(!@model.errors.empty?) %> 

<%= image_tag("error.png", :align => "top", :alt => "Error") -%> Oops, there was a problem editing your information.

<%= short_error_messages_for(:model) %>
<% end %>

然后在我的application_helper中,我迭代错误并生成一个简单的列表:

  def short_error_messages_for(object_name) object = instance_variable_get("@#{object_name}") if object && !object.errors.empty? content_tag("ul", object.errors.full_messages.collect { |msg| content_tag("li", msg) } ) else "" end end 

那段代码已经很老了,可能不是我现在写Ruby的方式,但是你得到了主旨。

您可以自己迭代模型.errors哈希,而不是使用错误帮助程序。