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
For Rails5 models are now subclasses of
ApplicationRecord
so to get list of all models in your app you do:Or shorter:
If you are in dev mode, you will need to eager load models before:
To avoid pre-load all Rails, you can do this:
require_dependency(f) is the same that
Rails.application.eager_load!
uses. This should avoid already required file errors.Then you can use all kind of solutions to list AR models, like
ActiveRecord::Base.descendants
This worked for me. Special thanks to all the posts above. This should return a collection of all your models.
I'm just throwing this example here if anyone finds it useful. Solution is based on this answer https://stackoverflow.com/a/10712838/473040.
Let say you have a column
public_uid
that is used as a primary ID to outside world (you can findjreasons why you would want to do that here)Now let say you've introduced this field on bunch of existing Models and now you want to regenerate all the records that are not yet set. You can do that like this
you can now run
rake di:public_uids:generate
If you want just the Class names:
Just run it in Rails console, nothing more. Good luck!
EDIT: @sj26 is right, you need to run this first before you can call descendants:
ActiveRecord::Base.connection.tables