方法引发ArgumentError

方法引发ArgumentError

本文介绍了为什么要' validate'方法引发ArgumentError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计,

我在(helloworld-y)Rails应用程序中无法获得validates_with的功能.通读原始 RoR指南站点的回调和验证器"部分,然后搜索stackoverflow什么都没有.

I can't get validates_with in my (helloworld-y) rails app to work. Read through "callbacks and validators" section of the original RoR guides site and searched stackoverflow, found nothing.

这是删除所有可能失败的代码后得到的简化代码.

Here's the stripped-down version of code I got after removing everything that can fail.

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指南中具有非常相似的代码段.然后我们转到rails console并在验证新记录时得到ArgumentError:

Looks like textbook example, right? They have the very similar snippet on RoR guides. Then we go to the rails console and get an ArgumentError while validating new record:

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/ruby-1.9.2-p180@wimmie/gems/activesupport-3.0.7/lib/active_support/callbacks.rb:315:in `_callback_before_43'

我知道我想念什么,但是呢?

I know I'm missing something, but what?

(注意:为避免将BareBonesValidator放入单独的文件中,我将其放在model/unvalidable.rb上方).

(NB: To avoid putting BareBonesValidator into separate file I left it atop model/unvalidable.rb).

推荐答案

validate函数应将记录作为参数(否则,您将无法在模块中访问它).该指南中没有提供,但是官方文档是正确的.

The validate function should take the record as parameter (otherwise you can't access it in the module). It's missing from the guide but the official doc is correct.

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

并且它已经在边缘指南中得到解决.

And it's already fixed in the edge guide.

这篇关于为什么要&amp;#39; validate&amp;#39;方法引发ArgumentError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:48