试图创建自定义验证方法,但得到错误
wrong number of arguments (0 for 1..3)
我想验证邮政编码的格式,但提供一个自定义的错误消息,而不是我在做时得到的消息
validates_format_of :postcode, with: /A^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$z/i, message: 'Please check your postcode'
这将给出的错误消息
postcode Please check your postcode
所以我想我可以做这个
class User < ActiveRecord::Base
validate :format_postcode
def format_postcode
regexp = /A^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$z/i
if !postcode.match(regexp)
errors.add[:base] << "Please check your Postcode"
end
end
end
但这是抛出错误
我在这里做错了什么?
感谢
问题出在这条线上
errors.add[:base] << "Please check your Postcode"
应该是
errors.add :base, "Please check your Postcode"
正如错误消息所示,add
是一个接受1..3个参数的方法,而不是数组的getter。