您的验证器应命名为UrlValidator
( camelized 的结果'url'
):
# Validator for the `url` attribute
class UrlValidator< ActiveModel::EachValidator
def validate_each(record, attribute, value)
# to be implemented
end
end
def Foo < ActiveRecord::Base
validates :url, :presence => true
end
链接到文档
或者,要坚持使用名称URLValidator
,您可以使用validates_with
:
class URLValidator< ActiveModel::EachValidator
def validate(record)
# check on record.url, to be implemented
end
end
def Foo < ActiveRecord::Base
validates_with URLValidator
end
或更通用的版本(如果属性的名称并不总是url
)
class URLValidator< ActiveModel::EachValidator
def validate(record)
value = record.send(options[:on])
# check value, to be implemented
end
end
def Foo < ActiveRecord::Base
validates_with URLValidator, :on => :url
end