Reputation: 2410
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
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
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
Reputation: 7995
Execute Rails.application.eager_load!
before calling the .descendants method.
Upvotes: 1
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