在我的单表继承模型中,我重写了基本模型中的inherited
方法,以便所有后代模型都可以通过基本模型的名称识别。下面的代码用于为所有继承的类向 model_name 方法添加重写。
def self.inherited(child)
child.instance_eval do
def model_name
BaesModelDefinition.model_name
end
end
end
我注意到这在 Rails 3.2.3 中产生了弃用警告:
DEPRECATION WARNING: It looks like something (probably a gem/plugin) is overriding
the ActiveRecord::Base.inherited method. It is important that this hook executes so
that your models are set up correctly. A workaround has been added to stop this
causing an error in 3.2, but future versions will simply not work if the hook is
overridden.
我可以使用其他方法来解决model_name问题吗?
答案很简单。只需向重写方法添加一个super
即可。
def self.inherited(child)
child.instance_eval do
def model_name
BaesModelDefinition.model_name
end
end
super
end