Created
December 12, 2012 08:20
-
-
Save chechaoyang/4266045 to your computer and use it in GitHub Desktop.
在某些特殊情况下,会出现这种需求:你希望清除掉 Model 中继承来的 validators。 (慎用!!小心因两个 Model 中的校验规则不一致,导致产生脏数据!) (activemodel 3.2.x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
module ClearActiveModelValidators | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# 清除指定属性上的 validators | |
# 参数说明(请全部使用 symbol): | |
# :all 清除所有属性上的 validators | |
# 属性名列表 清除指定属性上的 validators | |
# | |
# 示例: | |
# 1. 清除所有继承来的 validators | |
# class Person < User | |
# include ClearActiveModelValidators | |
# | |
# clear_validators_on :all | |
# | |
# validates :name, presence: true | |
# end | |
# | |
# 2. 清除指定属性上的 validators | |
# class Person < User | |
# include ClearActiveModelValidators | |
# | |
# clear_validators_on :name, :email | |
# | |
# validates :name, presence: true | |
# end | |
def clear_validators_on(*args) | |
if args == [:all] | |
self._validators = Hash.new { |h,k| h[k] = [] } | |
else | |
args.each { |attr_name| self._validators.delete(attr_name) } | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment