我正在 Rails 指南 ( http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations ) 中进行自定义验证,但我无法理解这里发生的情况。如何使用 EmailValidator?它在哪里被调用?
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
record.errors[attribute] << (options[:message] || "is not an email")
end
end
end
class Person < ActiveRecord::Base
validates :email, presence: true, email: true
end
所有代码都去哪里了?
最佳答案
您执行传递散列的validates
方法。当哈希被传递时,此方法会对其进行迭代,并为每个键实例化名称与给定键匹配的验证器。因此,如果您传递 presence: true
,它会实例化 PresenceValidator
的新实例,类似地,confirmation: true
实例化 ConfirmationValidator
。如果 value 不是 true
,而是哈希值,则它会被传递给验证器并存储在实例变量 @options
中,该变量由 options
访问> 读者。
关于ruby - Rails 4 自定义验证器说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22947174/