2011-05-02 77 views
5

道歉,如果這是一個非常常見和/或荒謬的問題;我發誓我已經多次閱讀文檔,並且所有內容似乎都集中在ActiveRecord上,以至於他們已經擺脫了創建或編輯模型數據之外的其他表單路徑。Rails 3:顯示窗體的驗證錯誤(不保存ActiveRecord模型)

以一個輸入爲例來控制一些統計數據的提取和顯示。爲了驗證此表單的用戶輸入,Rails提供了哪些內容,哪些記錄不會調用save?事情是這樣:

  • :email必須爲電子郵件地址
  • :num_products必須爲正整數
  • :gender必須是 「M」 或 「F」 的一個
  • :temperature必須在-10和120

等等等等(那種東西,在大多數web框架標配)...

有沒有什麼在Rails中爲我執行這個任意驗證和一些視圖助手來顯示錯誤列表,或者是一切與ActiveRecord?

道歉,如果我在文檔中忽略了這一點,但thisthis並沒有真正覆蓋它,至少在疲倦的眼睛可以告訴。

劃痕頭

多虧了羅布的答案,這裏是我想出。我創建了一個實用程序類(恰當地命名爲Validator),它只是嵌入到我的控制器中,用於任何需要它的事物。

module MyApp 

    class Validator 
     include ActiveModel::Validations 
     include ActiveModel::Conversion 
     extend ActiveModel::Naming 

     def initialize(attributes = {}) 
      super 
      attributes.each { |n, v| send("#{n}=", v) if respond_to?("#{n}=") } 
     end 
    end 

end 

現在控制器,例如,只定義有點直列類:

class LoginController < ApplicationController 
    class AuthenticationValidator < MyApp::Validator 
     attr_accessor :email 
     attr_accessor :password 
     validates_presence_of :email, :message => "E-mail is a required field" 
     validates_presence_of :password, :message => "Password cannot be blank" 
    end 

    def authenticate 
     if request.post? 
      @validator = AuthenticationValidator.new(params) 
      if @validator.valid? 
       # Do something meaningful 
      end 
     end 
    end 

感覺有點不必要的堅持每一個組驗證規則在自己.rb當邏輯更多的是面向控制器的恕我直言。可能有更簡潔的寫法,但我對Ruby和Rails很新。

回答

6

是的,它可以很容易地完成。

您可以使用它的validations API。

作爲一個例子,這裏是一個聯繫我們的模型,我用於一個沒有使用ActiveRecord的應用程序。

class ContactUs 
    include ActiveModel::Validations 
    include ActiveModel::Conversion 
    extend ActiveModel::Naming 

    attr_accessor :name, :email, :subject, :message 
    validates_presence_of :name, :email, :message, :subject 
    validates_format_of :email, :with => /\A[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}\z/ 
    def initialize(attributes=nil) 
    attributes.each do |name, value| 
     send("#{name}=", value) 
    end unless attributes.nil? 
    end 

    def persisted? 
    false 
    end 
end 
+0

非常好,謝謝!我會選擇這個除外:)我假設我需要閱讀的是API參考中的'ActiveModel :: Validations'? :)編輯|對不起,忽略了嵌入式鏈接。 – d11wtq 2011-05-02 14:21:43

+0

這正是我需要的,謝謝。我使用這種方法來創建更通用的「Validator」抽象類,以從includes/initialize方法中移除樣板代碼。 – d11wtq 2011-05-02 15:05:00

0

模型上有一個有效的方法,它會觸發驗證。

so instead model.save,try model.valid?

+0

我特別想知道如果我可以在用戶輸入上進行驗證,而不是在模型上進行驗證。假設我根本沒有加載模型,而且實際上我正在與Twitter API進行交互......如何在進行API調用之前驗證用戶輸入?我知道我可以手動完成,但它似乎肯定必須在那裏? :) – d11wtq 2011-05-02 14:16:26

+0

另一種情況是像用戶登錄,其中的字段是「電子郵件」和「密碼」,並且如果「電子郵件」參數看起來不像電子郵件地址,則您想失敗表單驗證。在這一點上,你沒有一個模型來驗證;你所擁有的只是一些用戶輸入。 – d11wtq 2011-05-02 14:18:15

+0

哦,對不起,我不明白這個問題。我看到Rob已經正確回答了這個問題,所以請查看他的答案。 – sparrovv 2011-05-02 14:22:18

相關問題