跳过Model中的某些validation方法
我正在使用Rails v2.3
如果我有一个型号 :
class car < ActiveRecord::Base validate :method_1, :method_2, :method_3 ... # custom validation methods def method_1 ... end def method_2 ... end def method_3 ... end end
如上所示,我有3种自定义validation方法 ,我将它们用于模型validation。
如果我在此模型类中有另一个方法,它保存模型的新实例,如下所示:
# "flag" here is NOT a DB based attribute def save_special_car flag new_car=Car.new(...) new_car.save #how to skip validation method_2 if flag==true end
我想跳过这个特定方法中method_2
的validation来保存新车, 如何跳过某些validation方法?
将模型更新为此
class Car < ActiveRecord::Base # depending on how you deal with mass-assignment # protection in newer Rails versions, # you might want to uncomment this line # # attr_accessible :skip_method_2 attr_accessor :skip_method_2 validate :method_1, :method_3 validate :method_2, unless: :skip_method_2 private # encapsulation is cool, so we are cool # custom validation methods def method_1 # ... end def method_2 # ... end def method_3 # ... end end
然后在你的控制器中放:
def save_special_car new_car=Car.new(skip_method_2: true) new_car.save end
如果你得到:flag
通过控制器中的params变量:flag
,你可以使用
def save_special_car new_car=Car.new(skip_method_2: params[:flag].present?) new_car.save end
条件validation的基本用法是:
class Car < ActiveRecord::Base validate :method_1 validate :method_2, :if => :perform_validation? validate :method_3, :unless => :skip_validation? def perform_validation? # check some condition end def skip_validation? # check some condition end # ... actual validation methods omitted end
查看文档以获取更多详细信息。
调整它到您的screnario:
class Car < ActiveRecord::Base validate :method_1, :method_3 validate :method_2, :unless => :flag? attr_accessor :flag def flag? @flag end # ... actual validation methods omitted end car = Car.new(...) car.flag = true car.save
在validation中使用块,例如:
validates_presence_of :your_field, :if => lambda{|e| e.your_flag ...your condition}
根据天气标志为假,使用方法save(false)
跳过validation。