跳过模型中的某些验证方法 [英] skip certain validation method in Model
本文介绍了跳过模型中的某些验证方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 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 种自定义验证方法,我将它们用于模型验证.
As you see above, I have 3 custom validation methods, and I use them for model validation.
如果我在这个模型类中有另一个方法来保存模型的新实例,如下所示:
If I have another method in this model class which save an new instance of the model like following:
# "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
的验证,如何跳过某些验证方法?
I would like to skip the validation of method_2
in this particular method for saving new car, how to skip the certain validation method?
推荐答案
将您的模型更新为此
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
然后在您的控制器中输入:
Then in your controller put:
def save_special_car
new_car=Car.new(skip_method_2: true)
new_car.save
end
如果您通过控制器中的 params 变量获取 :flag
,则可以使用
If you're getting :flag
via params variable in your controller, you can use
def save_special_car
new_car=Car.new(skip_method_2: params[:flag].present?)
new_car.save
end
这篇关于跳过模型中的某些验证方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文