I have a whole bunch of child classes that inherit from a parent class via single-table-inheritance in my Rails app. I\'d like a way to get an array of all the child classes tha
In your config/environments/development.rb
Rails.application.configure do
config.eager_load = false
end
U can change false to true, and then in your console to do
Class.subclasses
or
Class. descendants
here is the difference between subclasses and descendants
subclasses:
class Foo; end
class Bar < Foo; end
class Baz < Bar; end
Foo.subclasses # => [Bar]
descendants:
class C; end
C.descendants # => []
class B < C; end
C.descendants # => [B]
class A < B; end
C.descendants # => [B, A]
class D < C; end
C.descendants # => [B, A, D]
ParentClass.subclasses.map(&:name)
This will do it in one SQL query:
# SELECT DISTINCT type FROM objects
Object.uniq.pluck(:type)
You need to eager load the classes, as stated in: https://github.com/rails/rails/issues/3364
ActionDispatch::Reloader.to_prepare do
Rails.application.eager_load!
end
Then you will be able to use:
YourClass.subclasses
or
YourClass.descendants
Note, their is a more efficient way to implement Dave G's method above..
Object.select(:type).map(&:type).uniq
This first sends marshaled objects that only have the "type" attribute from the DB, which takes WAY less memory, then plucks only the types into an array that you can then uniq on. I'm sure there is an infinitely more efficient pure SQL way to do this though.
Assuming there is at least one of each of object extant in the table:
Object.all.uniq{|x| x.type}.collect(&:type)