swapab
swapab

Reputation: 2410

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 ?

Upvotes: 4

Views: 2394

Answers (4)

oma
oma

Reputation: 40800

Old Q, but for anyone else like me who get confused with empty lists for subclasses MyClass.subclasses => []

You need to explicitly set the dependency to your MySubclass class.

class MyClass < ApplicationRecord
end
require_dependency 'my_subclass'

$ MyClass.subclasses
=> ['MySubclass']

https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoloading-and-sti

Upvotes: 6

Abibullah Rahamathulah
Abibullah Rahamathulah

Reputation: 2891

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

Upvotes: 8

scarver2
scarver2

Reputation: 7995

Execute Rails.application.eager_load! before calling the .descendants method.

Upvotes: 1

swapab
swapab

Reputation: 2410

This helped me

config.autoload_paths += %W( #{config.root}/app/models/listings )

Taken from here - http://hakunin.com/rails3-load-paths

Upvotes: 0

Related Questions