如何在 rails 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
和一个派生模型(底层数据库表有一个 type
字段 - 这是简单的 rails STI)
and a derived model (the underlying database table has a type
field - this is simple rails STI)
class DerivedModel < BaseModel
end
DerivedModel
将以良好的面向对象方式继承 BaseModel
的所有行为,包括 validates_presence_of :parent_id
.我想关闭 DerivedModel
的验证,并防止回调方法触发,最好不要修改或以其他方式破坏 BaseModel
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
最简单、最可靠的方法是什么?
What's the easiest and most robust way to do this?
推荐答案
我喜欢使用以下模式:
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
如果 rails 提供一个 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.
这篇关于如何在 rails STI 派生模型中禁用验证和回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!