如何在Rails中更改" 3个错误,禁止保存此foobar"验证消息?
时间:2020-03-06 14:38:37 来源:igfitidea点击:
在我的rails应用程序中,我在活动记录对象中使用了验证帮助器,它们很棒。出现问题时,我会在我的网页上看到标准的" 3个错误禁止保存此foobar"以及个别问题。
有什么办法可以用我自己的方法覆盖此默认消息?
解决方案
我们可以遍历模型.errors可以自己哈希而不是使用错误帮助器。
通常,模型中的" validates_"方法都可以通过:message =>" My Validation Message"参数来传递。
我通常将错误包装在这样的东西中:
<% if([email protected]?) %> <div id="error_message"> <h2> <%= image_tag("error.png", :align => "top", :alt => "Error") -%> Oops, there was a problem editing your information. </h2> <%= short_error_messages_for(:model) %> </div> <% 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的方式,但是主旨是。
我们用来显示错误的error_messages_for帮助程序接受:header_message选项,该选项使我们可以更改默认标题文本。如:
error_messages_for 'model', :header_message => "You have some errors that prevented saving this model"
RubyOnRails API是朋友。

