2

I would like to perform some checking on the database resources only when the app starts/restarts (if any new migrations happen in between) by calling:

resources = ActiveRecord::Base.send(:subclasses).map { |subclass| subclass.name }

I tried inserting this code at different steps of the initialization process without any success (getting an empty array as a result). Why? And where should I insert it?

If I perform this checking in the ApplicationController , it will be always be executed. I only need to run it once after boot.

Where can I insert it?

demongolem
  • 9,474
  • 36
  • 90
  • 105
  • 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) – Raffael Oct 15 '15 at 18:06
  • I read all posts about it... it seems I forgot the eager_load! to actually get some results..; –  Oct 16 '15 at 07:09

1 Answers1

2

Compiling the gist of answers other people have given before:

In the development environment your model classes will not be eager loaded. Only when you invoke some code that references a model class, the corresponding file will be loaded. (Read up on 'autoloading' for further detail.)

So if you need to do some checks upon startup of the rails server, you can manually invoke

Rails.application.eager_load!

and after that get a list of all model classes with

model_classes = ActiveRecord::Base.descendants

For a list of model names associated with their database tables, you might use

model_classes.map{ |clazz| [clazz.model_name.human, clazz.table_name] }.sort

You can put your code in an arbitrarily named file in the config/initializers directory. All ruby files in that directory will get loaded at startup in alphabethical order.

The eager loading will of course take some time and thus slow down server and console start-up in the development environment a bit.

Other approaches such as parsing a list of filenames in the app/models directory are not reliable in more complex Rails applications.

If in a Rake task, make sure your Application is properly initialized before you send eager_load!. To that end, let your rake task depend on :environment.

HTH!

Raffael
  • 2,639
  • 16
  • 15
  • thanks a lot... that's what I actually need to do .. totally forgot the eager_load! in my different tries... so I always got an empty array whenever i put the code... Thanks for the tip about the list of model names, I'll keep a note about it –  Oct 16 '15 at 07:02