Ruby on rails 3 为什么';验证';方法引发参数错误?
各位 在我的(helloworld-y)rails应用程序中,我无法使用验证\u。通读原始文件的“回调和验证程序”部分并搜索stackoverflow,未发现任何内容 这是我在删除所有可能失败的代码后得到的精简版本Ruby on rails 3 为什么';验证';方法引发参数错误?,ruby-on-rails-3,validation,activerecord,arguments,Ruby On Rails 3,Validation,Activerecord,Arguments,各位 在我的(helloworld-y)rails应用程序中,我无法使用验证\u。通读原始文件的“回调和验证程序”部分并搜索stackoverflow,未发现任何内容 这是我在删除所有可能失败的代码后得到的精简版本 class BareBonesValidator < ActiveModel::Validator def validate # irrelevant logic. whatever i put here raises the same error - ev
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
我知道我错过了什么,但是什么
(注意:为了避免将
BareBonesValidator
放在单独的文件中,我将其放在model/unvalidable.rb
顶部。)错误ArgumentError:参数数量错误(1代表0)
表示使用1
参数调用了validate
方法,但该方法已定义为使用0
参数
因此,请定义如下所示的验证方法,然后重试:
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
class BareBonesValidator
验证功能应将记录作为参数(否则您无法在模块中访问它)。指南上没有,但它是正确的
class BareBonesValidator < ActiveModel::Validator
def validate(record)
if some_complex_logic
record.errors[:base] = "This record is invalid"
end
end
end
class BareBonesValidator
编辑:它已经被修复。欢迎!我看你是新来的。请注意,如果你发现答案解决了你的问题,那么这样做的方法就是接受并投票给你得到的答案。也请阅读常见问题。@zabba-谢谢。现在,也许你可以帮我回答一个与礼仪相关的问题。。。。你看,威尔特兰特的回答更简洁,但你的回答继续解释了ArgumentError
,这对未来的读者很有用。所以我接受了他的回答,然后把你的一些信息粘贴到了他的邮箱里。可以吗?)通常你不应该编辑答案。而不是为了从其他答案中创建一个“完整”答案。我想编辑答案只是修正打字错误/语法是正确的做法。对于其他问题,您应该在该答案上留下评论。@Michaël Witrant提到的一件事我忘记了,那就是如何在validate
方法中“设置错误”。@zabba-明白了,我错了。谢谢你的更正。
class BareBonesValidator < ActiveModel::Validator
def validate(record)
if some_complex_logic
record.errors[:base] = "This record is invalid"
end
end
end