5

在我的单表继承模型中,我重写了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 问题吗?

4

1 回答 1

6

答案很简单。只需将 a 添加super到覆盖方法即可。

  def self.inherited(child)
    child.instance_eval do
      def model_name
        BaesModelDefinition.model_name
      end
    end
    super
  end
于 2012-05-27T13:21:28.237 回答