2012-02-28 103 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,結果相同。)