Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Table Inheritance (STI) parent ActiveRecord .subclasses .descendants returns empty

I have a STI in place for 10 models inheriting from one ActiveRecord::Base model.

class Listing::Numeric < ActiveRecord::Base
end

class Listing::AverageDuration < Listing::Numeric
end

class Listing::TotalViews < Listing::Numeric
end

There are 10 such models those inherit from Listing::Numeric

In rails console, when I try for .descendants or .subclasses it returns an empty array.

Listing::Numeric.descendants
=> []

Listing::Numeric.subclasses
=> []

Ideally this should work.

Any ideas why its not returning the expected subclasses ?

like image 251
swapab Avatar asked Dec 06 '22 04:12

swapab


1 Answers

This will work only if all the inherited classes are referenced in some running code as rails will load the classes when required then only it will be added as descendants

For eg:

Listing::Numeric.descendants.count
=> 0

Listing::AverageDuration
Listing::TotalViews

Listing::Numeric.descendants.count
=> 2
like image 194
Abibullah Rahamathulah Avatar answered Feb 22 '23 23:02

Abibullah Rahamathulah