1

I am currently very confused by using descendants for ActiveRecord::Base-Objects. I have browsed the internet and tested all solutions but none of them fits my needs.

What i want to do: Get an Array of all subclasses of ActiveRecord::Base, including subclasses of these subclasses, e.g.

Entity < ActiveRecord::Base
ChildEntity < Entity

Property < ActiveRecord::Base

My current problems: ActiveRecord::Base.descendants does NOT list all the classes inheriting from ActiveRecord::Base. Perhaps the fault is on my side: here my code.

 def all_entities
   rec_all_entities(ActiveRecord::Base)
 end

 def rec_all_entities(motherEntity)
    logger.debug("mother: " + motherEntity.to_s + " descendants: " + motherEntity.descendants.to_s)
    motherEntity.descendants.each do |childEntity|
      rec_all_entities(childEntity)
    end
 end  

For debbuging purpose I'm just printing out. I'm using Rails 3.

I think the fault must lie in my code. I'm calling the method currently just in the view with <% all_entities %>

Thanks for your help.

tubtub
  • 11
  • 1
  • 2
  • as I can see, ActiveRecord::Base.descendants should list all descendants (even sub-subclasses). But anyhow it doesnt collect all descendants - the maximum is 4 entities - my model has 7 – tubtub Jul 17 '11 at 17:44
  • Possible duplicate of [Is there a way to get a collection of all the Models in your Rails app?](http://stackoverflow.com/questions/516579/is-there-a-way-to-get-a-collection-of-all-the-models-in-your-rails-app) – Bryan Ash Nov 10 '16 at 14:44

2 Answers2

7

This worked well for me. Also, taken from Is there a way to get a collection of all the Models in your Rails app?

> Rails.application.eager_load!
> ActiveRecord::Base.descendants
Community
  • 1
  • 1
RubeOnRails
  • 1,153
  • 11
  • 22
1

If you're in development mode you must touch each model before it will be picked up by desendants

Taken from Is there a way to get a collection of all the Models in your Rails app?

Community
  • 1
  • 1
philt5252
  • 939
  • 7
  • 19