2014-06-07 41 views
5

我在我的Rails 4應用程序中使用Simple_form。如何使用Simple_form但沒有模型顯示驗證錯誤消息?

如何在與模型無關的視圖中顯示錯誤消息?

我想要得到與基於模型的其他視圖相同的結果。

現在,這是在視圖的代碼:

<%= simple_form_for(:registration, html: { role: 'form' }, :url => registrations_path) do |f| %> 

    <%= f.error_notification %> 

    <%= f.input :name, :required => true, :autofocus => true %> 
    <%= f.input :email, :required => true %> 
    <%= f.input :password, :required => true %> 
    <%= f.input :password_confirmation, :required => true %> 

    <%= f.button :submit %> 

<% end %> 

在「正常」的視圖(即,與一個模型)的線<%= f.error_notification %>顯示錯誤。

我應該怎樣在我的控制器中初始化Simple_form使用的內容來顯示錯誤?

感謝

回答

0

simple_form_for助手必須換一種模式。但僅僅因爲我們說這並不意味着它必須是一個由數據庫表支持的ActiveRecord模型。您可以自由創建不受數據庫支持的模型。在Rails 3+中,這樣做的方法是讓您的課程包含您需要的組件,從ActiveModelThis SO post解釋瞭如何用一個例子來做到這一點(我確信有很多其他的)。一旦你有一個包含ActiveModel::Validation的模型,你可以添加到errors集合,然後f.error_notification語句將輸出你在表背後模型中的錯誤。

TL; DR:創建一個非ActiveRecord,非表支持的模型,然後將其視爲一個普通的舊模型,並且表單應該做正確的事情。

+0

謝謝你的回答。可以在不使用模型的情況下使用Simple_form:只需使用'':'symbol''''作爲第一個參數。實際上,我的控制器/視圖工作得很好,我只想顯示基於模型的視圖(由我的控制器生成)作爲視圖的錯誤消息。無論如何,感謝您的想法,我會看看這個解決方案。 –

+0

啊,很高興知道。沒有意識到關於simple_form。不過,'error_notification'助手很可能在包裝對象上尋找'errors'方法。它是有道理的,一個符號不會對此作出迴應。我想知道你是否可以用一個''Struct'對象來響應'errors'。也許,但它仍然像是一個非數據庫支持的模型對我來說會更好。 – pdobb

0

使用client_side_validations的寶石,它是簡單,你只做到 -

<%= simple_form_for(:registration, html: { role: 'form' }, :url => registrations_path) , :validate => true do |f| %> 

但是你需要在模型中加入驗證也。

+0

謝謝。我會測試這個。但我沒有一個模型。只有一個控制器和視圖。 –

5

簡單形式不支持「開箱即用」功能。但是你可以用這樣的初始化一個「猴子補丁」添加它(免責聲明 - 這似乎爲我的簡單測試情況下工作,但還沒有被徹底的測試):

// Put this code in an initializer, perhaps at the top of initializers/simple_form.rb 
module SimpleForm 
    module Components 
    module Errors 
     def has_errors? 
     has_custom_error? || (object && object.respond_to?(:errors) && errors.present?) 
     end 

     def errors 
     @errors ||= has_custom_error? ? [options[:error]] : (errors_on_attribute + errors_on_association).compact 
     end 
    end 
    end 
end 

module SimpleForm 
    class ErrorNotification 
    def has_errors? 
     @options[:errors] || (object && object.respond_to?(:errors) && errors.present?) 
    end 
    end 
end 

然後你就可以添加錯誤(請注意是否通過設置'errors:true'來顯示錯誤通知,您必須執行自己的檢查以確定是否存在錯誤,並動態添加錯誤):

=simple_form_for :your_symbol do |f| 
    =f.error_notification errors: true 
    =f.input :item1, as: :string, error: "This is an error on item1" 
    =f.input :item2, as: :string, error: "This is an error on item2" 
相關問題