Is there a way that you can get a collection of all of the Models in your Rails app?
Basically, can I do the likes of: –
Models.each do |model|
puts model.class.name
end
activerecordcollectionsmodelruby-on-rails
Is there a way that you can get a collection of all of the Models in your Rails app?
Basically, can I do the likes of: –
Models.each do |model|
puts model.class.name
end
Best Answer
The whole answer for Rails 3, 4 and 5 is:
If
cache_classes
is off (by default it's off in development, but on in production):Then:
This makes sure all models in your application, regardless of where they are, are loaded, and any gems you are using which provide models are also loaded.
This should also work on classes that inherit from
ActiveRecord::Base
, likeApplicationRecord
in Rails 5, and return only that subtree of descendants:If you'd like to know more about how this is done, check out ActiveSupport::DescendantsTracker.