方法
实例公共方法
after_validation(*args, &block) 链接
定义一个在验证后立即调用的回调。
class Person
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
attr_accessor :name, :status
validates_presence_of :name
after_validation :set_status
private
def set_status
self.status = errors.empty?
end
end
person = Person.new
person.name = ''
person.valid? # => false
person.status # => false
person.name = 'bob'
person.valid? # => true
person.status # => true
源代码: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/validations/callbacks.rb, line 88 def after_validation(*args, &block) options = args.extract_options! options = options.dup options[:prepend] = true set_options_for_callback(options) set_callback(:validation, :after, *args, options, &block) end
before_validation(*args, &block) 链接
定义一个在验证之前立即调用的回调。
class Person
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
attr_accessor :name
validates_length_of :name, maximum: 6
before_validation :remove_whitespaces
private
def remove_whitespaces
name.strip!
end
end
person = Person.new
person.name = ' bob '
person.valid? # => true
person.name # => "bob"
源代码: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/validations/callbacks.rb, line 55 def before_validation(*args, &block) options = args.extract_options! set_options_for_callback(options) set_callback(:validation, :before, *args, options, &block) end