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)
Share:
11,346
gespinha
Author by

gespinha

Updated on July 16, 2022

Comments

  • gespinha
    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
    Kristján over 8 years
    No need for send, #subclasses is public.
  • Arup Rakshit
    Arup Rakshit over 8 years
    you don't need send .. it is a public method
  • gespinha
    gespinha over 8 years
    Is there any abbreviation for the ActiveRecord::Base snippet? Everytime I need something from the base layer, do I need to use this?
  • eirikir
    eirikir over 8 years
    Does 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 invoke Agency, then I get [User, User::HABTM_Agencies, Agency, Agency::HABTM_Users]
  • boulder
    boulder over 8 years
    This 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
    Lex over 4 years
    I 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
    Masa Sakano almost 3 years
    The 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).