Active Model EachValidator
EachValidator
是一个验证器,它会遍历选项哈希中给出的属性,调用 validate_each
方法,传入记录、属性和值。
所有 Active Model 验证都建立在此验证器之上。
方法
- C
- N
- V
属性
[R] | attributes |
类公共方法
new(options) 链接
返回新的验证器实例。所有选项都可通过 options
读取器获得,但 :attributes
选项将被移除,而通过 attributes
读取器获得。
源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 140 def initialize(options) @attributes = Array(options.delete(:attributes)) raise ArgumentError, ":attributes cannot be blank" if @attributes.empty? super check_validity! end
实例公共方法
check_validity!() 链接
钩子方法,由初始化程序调用,允许验证提供的参数是否有效。例如,当提供无效选项时,你可以引发 ArgumentError
。
源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 168 def check_validity! end
validate(record) 链接
对提供的记录执行验证。默认情况下,这将调用 validate_each
来确定有效性,因此子类应使用验证逻辑覆盖 validate_each
。
源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 150 def validate(record) attributes.each do |attribute| value = record.read_attribute_for_validation(attribute) next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) value = prepare_value_for_validation(value, record, attribute) validate_each(record, attribute, value) end end
validate_each(record, attribute, value) 链接
在子类中使用验证逻辑覆盖此方法,在必要时将错误添加到记录的 errors
数组中。
源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 161 def validate_each(record, attribute, value) raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method" end