Is there a way to detect all the models used in a Rails app that have database tables? I've tried to detect all models in a Rails application by reading all the models off of the app/models directory and simply read all the files in that directory. However, I do not think this is the best approach and have spent a considerable amount of time researching this but I haven't gotten a better answer yet. Can anyone help me with this. Many thanks!
            Asked
            
        
        
            Active
            
        
            Viewed 328 times
        
    3
            
            
        - 
                    1Duplicate? http://stackoverflow.com/questions/516579/is-there-a-way-to-get-a-collection-of-all-the-models-in-your-rails-app – Doon Mar 08 '11 at 18:58
 - 
                    Thanks Doon. I've tried this method before and I was wondering if there is a better method. – RubyFanatic Mar 08 '11 at 19:07
 
2 Answers
4
            
            
        I'm assuming you are using ActiveRecord. If you are, here is how you go about getting a list of all ActiveRecord::Base subclasses:
ActiveRecord::Base.subclasses
You can also do the following:
dbmodels = []
ObjectSpace.each_object(Module){ |m| dbmodels << m if m.ancestors.include?(ActiveRecord::Base) && m != ActiveRecord::Base }
dbmodels should now contain all your ActiveRecord::Base models.
Keep in mind that in your development environment you won't get a full list of subclasses unless they have been loaded/used, so I would recommend performing this in your production environment instead, that way you can ensure that all your models have been loaded.
        Pan Thomakos
        
- 34,082
 - 9
 - 88
 - 85
 
0
            
            
        You first need to make sure that all the models are loaded:
Rails.application.eager_load!
In Rails 3, the ideal way to find all ActiveRecord descendants is with descendants:
ActiveRecord::Base.descendants
Then, select those with a table:
ActiveRecord::Base.descendants.select(&:table_name)
The basis for this was pulled from https://stackoverflow.com/a/10712838/15585.