2011-05-12 40 views
3

Folk,爲什麼這個'驗證'方法會引發一個ArgumentError?

我在我的(helloworld-y)rails應用程序中無法獲得validates_with的工作。仔細閱讀原始RoR guides site中的「回調和驗證器」部分,並搜索到了stackoverflow,但沒有發現任何內容。

下面是刪除所有可能失敗的代碼的精簡版本。

class BareBonesValidator < ActiveModel::Validator 
    def validate  
    # irrelevant logic. whatever i put here raises the same error - even no logic at all 
    end 
end 

class Unvalidable < ActiveRecord::Base 
    validates_with BareBonesValidator 
end 

看起來像教科書的例子吧?他們在RoR guides上有非常相似的片段。然後我們去rails console,並得到一個ArgumentError在驗證新的紀錄:

ruby-1.9.2-p180 :022 > o = Unvalidable.new 
=> #<Unvalidable id: nil, name: nil, created_at: nil, updated_at: nil> 
ruby-1.9.2-p180 :023 > o.save 
ArgumentError: wrong number of arguments (1 for 0) 
    from /Users/ujn/src/yes/app/models/unvalidable.rb:3:in `validate' 
    from /Users/ujn/.rvm/gems/[email protected]/gems/activesupport-3.0.7/lib/active_support/callbacks.rb:315:in `_callback_before_43' 

我知道我失去了一些東西,但什麼? (注意:爲避免將BareBonesValidator放入單獨的文件中,我將它留在model/unvalidable.rb之上)。

+0

歡迎!我看到你是新來的。請注意,如果您發現答案可以解決您的問題,那麼SO的工作方式就是接受並提升您獲得的答案。也閱讀常見問題解答。 – Zabba 2011-05-12 06:22:58

+0

@zabba - 謝謝。現在,也許你可以幫助我一個SO禮儀相關的問題....看,Wiltrant的答案是更簡潔,但你的解釋'ArgumentError'包含對未來的讀者有用。所以我接受了他的回答,然後把你的一些信息拷貝到他的信中。可以嗎?) – Eugene 2011-05-12 18:06:38

+0

通常你不應該編輯答案。而不是爲了從其他答案中創建一個「完整」答案。我想編輯答案只修復錯字/語法是正確的事情。對於其他一切,你應該在這個答案上留下評論。 @MichaëlWitrant提到的我忘記的一件事是如何在「驗證」方法中「設置錯誤」。 – Zabba 2011-05-12 18:36:34

回答

2

validate功能應該記錄爲參數(否則你不能訪問它的模塊中)。它在指南中缺失,但是the official doc是正確的。

class BareBonesValidator < ActiveModel::Validator 
    def validate(record) 
    if some_complex_logic 
     record.errors[:base] = "This record is invalid" 
    end 
    end 
end 

編輯:它已經固定在the edge guide

1

錯誤ArgumentError: wrong number of arguments (1 for 0)意味着該validate方法被調用與1參數但該方法已經定義採取0參數。

所以定義validate方法如下圖所示,然後再試一次:

class BareBonesValidator < ActiveModel::Validator 
    def validate(record) #added record argument here - you are missing this in your code 
    # irrelevant logic. whatever i put here raises the same error - even no logic at all 
    end 
end 
相關問題