如何禁用轨道STI导出模型中的验证和回调? [英] How can I disable a validation and callbacks in a rails STI derived model?
问题描述
给定一个模型
class BaseModel < ActiveRecord::Base
validates_presence_of :parent_id
before_save :frobnicate_widgets
end
和一个派生模型(底层数据库表有一个类型
字段 - 这是简单的轨道STI)
and a derived model (the underlying database table has a type
field - this is simple rails STI)
class DerivedModel < BaseModel
end
DerivedModel
在良好的OO时尚继承从 BaseModel
,包括 validates_presence_of:parent_id
的所有行为。我想为 DerivedModel
关闭验证,并防止回调方法触发,最好不要修改或破坏 BaseModel $ c $
DerivedModel
will in good OO fashion inherit all the behaviour from BaseModel
, including the validates_presence_of :parent_id
. I would like to turn the validation off for DerivedModel
, and prevent the callback methods from firing, preferably without modifying or otherwise breaking BaseModel
推荐答案
我喜欢使用以下模式:
class Parent < ActiveRecord::Base
validate_uniqueness_of :column_name, :if => :validate_uniqueness_of_column_name?
def validate_uniqueness_of_column_name?
true
end
end
class Child < Parent
def validate_uniqueness_of_column_name?
false
end
end
提供了一个skip_validation方法来解决这个问题,但这种模式可以很好地处理复杂的交互。
It would be nice if rails provided a skip_validation method to get around this, but this pattern works and handles complex interactions well.
这篇关于如何禁用轨道STI导出模型中的验证和回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!