【发布时间】:2013-06-24 00:54:42
【问题描述】:
我试图在 Ruby on Rails 中创建一个可以扩展的自定义验证器类。但是,我无法让它同时使用子类和超类的验证。 这个例子将阐明我想要实现的目标:
超类
class NameValidator < ActiveModel::EachValidator
def validate_each (record, attribute, value)
#Checks to see if the incoming string is free of any numerical characters
if value.match(/\A[+-]?\d+\Z/)
record.errors[attribute] << "String must contain no numerical characters"
end
end
end
子类
class SevenNameValidator < NameValidator
def validate_each (record, attribute, value)
# Checks and only allows 7 character strings to be validated
if value.length != 7
record.errors[attribute] << "String must be 7 characters exactly"
end
end
end
模型类
class User < ActiveRecord::Base
attr_accessible :firstname
validates :firstname, :seven_name => true
end
因此,如果测试字符串“hello”,则会出现错误 =>“字符串必须完全是 7 个字符”
但是,如果测试字符串“hello77”,则验证成功。
它不应该先从 NameValidator 检查它是否有数字?如果没有,我怎样才能让继承在自定义验证器中工作?我需要在我的验证器类中使用方法吗?一个例子将不胜感激,我搜索了很多,但我找不到自定义验证器的例子。
【问题讨论】:
-
您可能希望在
SevenNameValidator的 validate_each 中使用super。
标签: ruby-on-rails ruby ruby-on-rails-3 inheritance custom-validators