从ActiveRecord模型继承时防止STI

Mik*_*ike 29 ruby ruby-on-rails sti

在Rails 3.2.6上,我有一个继承自ActiveRecord :: Base的类:

class Section < ActiveRecord::Base
  ...
end
Run Code Online (Sandbox Code Playgroud)

当我从这个类继承时,Rails会假设我想要STI:

class AnotherSection < Section
   ..Rails assumes I have a type field, etc...
end
Run Code Online (Sandbox Code Playgroud)

我希望能够从Section类继承并使用子类作为普通的Ruby子类,而不需要Rails STI魔法.

有没有办法在从ActiveRecord::Base模型中进行子类化时阻止STI ?

Ver*_*cus 38

您可以通过禁用inheritance_column模型来实现此目的,如下所示:

class AnotherSection < Section
  # disable STI
  self.inheritance_column = :_type_disabled

end
Run Code Online (Sandbox Code Playgroud)

  • 那个,或任何不存在的列就足够了. (7认同)
  • self.inheritance_column = nil为我工作(但我很久以前就试过了,这是轨道3.2) (3认同)

sma*_*thy 10

接受的答案肯定会奏效,但推荐的(我敢说"正确":)方式是设置abstract_class:

class Section < ActiveRecord::Base
  self.abstract_class = true
end
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的方法,自Rails 1.1以来一直存在. (3认同)
  • 谢谢回复.是的,我只是想从具有"类型"列的模型中禁用STI,并且没有正确阅读上面的问题. (2认同)