Is there a way to find out all the Mongoid Models names in my rails app. I can find all the models just by getting all the file inside my app/models folder but i specifically want mongoid model names.
You can do this in Mongoid version 3.1 and higher: Mongoid.models
If you are in Rails' development mode where the models are not automatically loaded, run Rails.application.eager_load!
to load the entire application.
If your model classes are already loaded then you could list them by finding all the classes that include the Mongoid::Document module.
Object.constants.collect { |sym| Object.const_get(sym) }.
select { |constant| constant.class == Class && constant.include?(Mongoid::Document) }
or if you just want the class names:
Object.constants.collect { |sym| Object.const_get(sym) }.
select { |constant| constant.class == Class && constant.include?(Mongoid::Document) }.
collect { |klass| klass.name }
If you need to force your models to load before running this you can do so like this (in Rails 3):
Dir["#{Rails.root}/app/models/**/*.rb"].each { |path| require path }
(assuming all of your models are in app/models
or a sub-directory)
The problem with Mongoid.models
is that apparently only returns the already loaded models. I did the following experiment in the rails console (I have three models: Admin
, User
and Device
):
irb(main)> Mongoid.models
=> [Admin, User]
But if I instantiate the class Device
and then call the same method, I get a different result:
irb(main)> Device.last
=> #<Device _id: 52c697494d616308cf380000, type_code: "666", name: "My device">
irb(main)> Mongoid.models
=> [Admin, User, Device]
So this could represent a problem, specially if the method is called from a rake task. The Chris' solution works fine so I guess that is the best option at this moment :S (I can't got working the Steve's solution with Rails 4).
Here is a gist I coded to get all Mongoid models, and optionally filter them by superclass (say, if you want to only get models inheriting from a specific class).
https://gist.github.com/4633211
(compared to Steve solution, it's also working with namespaced models)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With