Rails STI - Prevent base class from instantiation

前端 未结 6 932
陌清茗
陌清茗 2021-01-01 11:06

Is there any way in a Rails STI situation to throw an error when the base class is Instantiated? Overriding initialize will do it but then that gets trickled down to the sub

6条回答
  •  灰色年华
    2021-01-01 11:23

    The answer by John Topley is actually wrong. Setting abstract_class = true in the base class will actually cause the child classes to stop setting their type automatically. Plus, unless you set_table_name in the base class, the child classes will complain their table does not exist.

    This is because the purpose of abstract_class=true is to set up inheritance when you are NOT using STI, and want to have an abstract class (class not backed by a db table) in your class hierarchy between ActiveRecord::Base and one or more model classes.

    Having initialize raise is one solution, also adding validates_presence_of :type to the base class is a solution.

    Note if you DO override initialize, you need to call super:

    def initialize(*args)
      raise "Cannot directly instantiate an AbstractUser" if self.class == AbstractUser
      super
    end
    

提交回复
热议问题