Rails console display all models
11,346
Solution 1
Try this:
ActiveRecord::Base.subclasses
This will return an array, so to get the name of the models only, you'd need to run:
ActiveRecord::Base.subclasses.map(&:name)
Solution 2
Just run:
Rails.application.eager_load!
ActiveRecord::Base.subclasses
Solution 3
I tried both the answers above, It does not work as expected. I got this result,
["User", "HABTM_Roles", "ApplicationRecord", "PublicActivity::ORM::ActiveRecord::Activity", "ApplicationRecordGlobal", "HABTM_Users", "UserSync"]
What worked for me was,
Rails.application.eager_load!
ApplicationRecord.subclasses.map(&:name)
Author by
gespinha
Updated on July 16, 2022Comments
-
gespinha almost 2 years
Is there a way in the
rails console
to display all rails models?Something like this:
Models.all
which results on this:
[Customer, Site, Page, Download]
-
Kristján over 8 yearsNo need for
send
,#subclasses
is public. -
Arup Rakshit over 8 yearsyou don't need
send
.. it is a public method -
gespinha over 8 yearsIs there any abbreviation for the
ActiveRecord::Base
snippet? Everytime I need something from the base layer, do I need to use this? -
eirikir over 8 yearsDoes this actually work at all times? When I try this, some models are not included until I use them in the code, and it includes some non-model classes that apparently do something with
has_and_belongs_to_many
. For example, I get [User
,User::HABTM_Agencies
], then I invokeAgency
, then I get [User
,User::HABTM_Agencies
,Agency
,Agency::HABTM_Users
] -
boulder over 8 yearsThis only works with loaded files. So in a development environment you'll only get a subset of the models. This is not a problem in production since models are eagerloaded. A possible solution would be to run
Dir["#{Rails.root}/app/models/**/*.rb"].each {|f| puts f; require File.basename f}
prior to running subclasses. -
Lex over 4 yearsI think the origonal answer is for an older version of rails. I'm using rails
gem 'rails', '~> 5.0.5'
and this worked for me. Nice find! -
Masa Sakano almost 3 yearsThe best answer is found in an answer to a very similar question, which works on Rails 3 to 6: stackoverflow.com/a/10712838/3577922 Note this accepted answer does not work on Rails 5+ (the question is tagged for Rails 4).