Why does this 'validate' method raise an ArgumentError?

送分小仙女□ 提交于 2019-12-22 09:53:39

问题


Folks,

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

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?

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


回答1:


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

Edit: And it's already fixed in the edge guide.




回答2:


Error ArgumentError: wrong number of arguments (1 for 0) means that the validate method was called with 1 argument but the method has been defined to take 0 arguments.

So define your validate method like below and try again:

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


来源:https://stackoverflow.com/questions/5973909/why-does-this-validate-method-raise-an-argumenterror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!