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
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
Assuming all models are in app/models and you have grep & awk on your server (majority of the cases),
It it faster than
Rails.application.eager_load!
or looping through each file withDir
.EDIT:
The disadvantage of this method is that it misses models that indirectly inherit from ActiveRecord (e.g.
FictionalBook < Book
). The surest way isRails.application.eager_load!; ActiveRecord::Base.descendants.map(&:name)
, even though it's kinda slow.I can't comment yet, but I think sj26 answer should be the top answer. Just a hint:
This works for Rails 3.2.18
This seems to work for me:
Rails only loads models when they are used, so the Dir.glob line "requires" all the files in the models directory.
Once you have the models in an array, you can do what you were thinking (e.g. in view code):
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.