2011-05-12 77 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 
相关问题