如果表单中存在语义错误(主要来自外部API),我想添加解释性消息,如下所示:
<%= semantic_form_for @order, :url => checkout_purchase_url, :html => {:class => 'payment'}, :wrapper_html => { :class => "field" } do |f| %>
<% if f.has_errors? %>
<p>There were errors that prevented your order from being submitted. If you need assistance, please contact us toll-free at <strong>1-800-555-5555</strong>.</p>
<%= f.semantic_errors %>
<% end %>
<% end %>
但是,has_errors?
是受保护的方法。有没有办法可以做到这一点?感谢。
答案 0 :(得分:3)
没有我想象的那么难。我通过检查对象而不是表单上的错误来修复它:
<% if @object.errors.any? %>
<p>There were errors that prevented your order from being submitted. If you need assistance, please contact us toll-free at <strong>1-800-555-5555</strong>.</p>
<%= f.semantic_errors %>
<% end %>
感谢那些观看过的人。
答案 1 :(得分:3)
如果您有嵌套属性,则不会看到与它们相关的任何错误。确保您获得所有基本错误和任何嵌套属性错误。确保您的模型包含:
validates_presence_of :nested_object
validates_associated :nested_object
并以您的形式:
f.semantic_errors *f.object.errors.keys
答案 2 :(得分:0)
为了完整性,如果您想在每个字段上显示类似的有用消息,这里有另一种方法:
./manage.py migrate
这为每个字段提供了格式良好且易于设置的错误列表。 (如果您愿意,可以使用semantic_errors而不是object.errors,结果相同。)