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

后端 未结 7 762
礼貌的吻别
礼貌的吻别 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]
    
    0 讨论(0)
  • 2021-02-07 12:38
    ParentClass.subclasses.map(&:name)
    
    0 讨论(0)
  • 2021-02-07 12:41

    This will do it in one SQL query:

    # SELECT DISTINCT type FROM objects
    Object.uniq.pluck(:type)
    
    0 讨论(0)
  • 2021-02-07 12:42

    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
    
    0 讨论(0)
  • 2021-02-07 12:50

    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.

    0 讨论(0)
  • 2021-02-07 12:52

    Assuming there is at least one of each of object extant in the table:

    Object.all.uniq{|x| x.type}.collect(&:type)
    
    0 讨论(0)
提交回复
热议问题