1

I am trying to implement STI as follows

module ModuleName
  class ParentName
    self.inheritance_column = 'column_name'
  end
end

module ModuleName
  class ChildName < ModuleName::ParentName
    class << self
      def find_sti_class(type_name)
        type_name = self.name
        super
      end

      def sti_name
        self.name.sub(/^.*:/,"")
      end
    end
end

When I try

ModuleName::ChildName.create(column_name: 'ChildName')

I am getting following error

ActiveRecord::SubclassNotFound: Invalid single-table inheritance type: ChildName is not a subclass of ModuleName::ChildName

I was trying to refer to solution provided here Rails STI: How to change mapping between class name & value of the 'type' column

Any help appreciated. Thanks.

Community
  • 1
  • 1
rohan
  • 1,606
  • 12
  • 21

2 Answers2

1

The mistake I was doing was specifying the inheritance column while creating ChildName.

wrong:-

ModuleName::ChildName.create(column_name: 'ChildName')

right:-

ModuleName::ChildName.create() 

It will automatically set column_name to 'ChildName' Specifying it will make rails think that ChildName is a parent class and will look for subclasses with name ChildName

rohan
  • 1,606
  • 12
  • 21
0
module ModuleName
  class ParentName
    self.inheritance_column = 'column_name'
  end
end

module ModuleName
  class ChildName << ParentName
    # ...
  end
end

When you declare a class inside a module it will automatically resolve the superclass to the same module.

Thus using ChildName << ModuleName::ParentName will try to resolve ModuleName::ModuleName::ParentName. If you want to explicitly state the superclass you would use ::ModuleName::ParentName.

max
  • 96,212
  • 14
  • 104
  • 165
  • Tried using both ChildName << ParentName as well as ChildName << ::ModuleName::ParentName . I am still getting the exact same error. – rohan Jul 25 '16 at 09:48