Get a list/array of child classes from Single Table Inheritance in Rails?

后端 未结 7 788
礼貌的吻别
礼貌的吻别 2021-02-07 11:49

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

7条回答
  •  广开言路
    2021-02-07 12:30

    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]
    

提交回复
热议问题