Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::Base.send(:descendants) doesn't return all models unless touched

Update: This problem no longer exists in Rails 3.2

I am trying to get an array containing all the models in my rails 3 application. I am trying:

ActiveRecord::Base.send(:descendants)

for the same. A similar discussion happened in the question: Is there a way to get a collection of all the Models in your Rails app?. As pointed out in one of the answers, we need to touch the models for the models to show up. That is precisely the problem I am facing.

There are more than a dozen models in my rails app, but

ActiveRecord::Base.send(:descendants) 

returns an array of size two. The array has just User and ActiveRecord::SessionStore::Session models. I don't get the other models untill I touch the model by touching, say invoking Comment.new How can I get all the models listed without touching all the models?

Another additional piece of information that might be useful is that I am using devise for authentication. Maybe devise is doing things in a desired way as far as User model is concerned and I am not doing those things with the other models.

Thanks a lot in advance.

like image 836
Satyaram B V Avatar asked Dec 12 '25 05:12

Satyaram B V


2 Answers

If cache_classes is on (by default it's on in development, not in production), run this first:

Rails.application.eager_load!
like image 200
dpaluy Avatar answered Dec 15 '25 21:12

dpaluy


You need to load the models first:

Dir[Rails.root + "app/models/**/*.rb"].each do |path|
    require path
end
like image 24
Martin Harrigan Avatar answered Dec 15 '25 20:12

Martin Harrigan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!