2012-02-28 91 views
1

如果存在的形式(主要来自外部API)语义错误,我想添加的说明信息,像这样:添加消息formtastic语义错误块

<%= 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?是一个受保护方法。有没有办法可以做到这一点?谢谢。

回答

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

感谢那些浏览过的人。

3

如果您有嵌套的属性,您将看不到与它们相关的任何错误。确保您获得所有基本错误和任何嵌套属性错误。确保您的模型包含:

validates_presence_of :nested_object 
validates_associated :nested_object 

,并在您的形式:

f.semantic_errors *f.object.errors.keys 
0

为了完整起见,这里是另一种方法,如果你想显示在每场类似的有用信息:

= f.label :title 
- if f.object.errors.any? 
.error = f.object.errors[:title].flatten.join(' and ') 
= f.text_field :title 

这为每个字段提供了格式良好且容易设计的错误列表。 (如果您愿意,可以使用semantic_errors而不是object.errors,结果相同。)

相关问题