Rails: How to list database tables/objects using the Rails console?

Ruby on-RailsConsole

Ruby on-Rails Problem Overview


I was wondering if you could list/examine what databases/objects are available to you in the Rails console. I know you can see them using other tools, I am just curious. Thanks.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You are probably seeking:

ActiveRecord::Base.connection.tables

and

ActiveRecord::Base.connection.columns('projects').map(&:name)

You should probably wrap them in shorter syntax inside your .irbrc.

Solution 2 - Ruby on-Rails

I hope my late answer can be of some help.
This will go to rails database console.

rails db

pretty print your query output

.headers on
.mode columns
(turn headers on and show database data in column mode )

Show the tables

.table

'.help' to see help.
Or use SQL statements like 'Select * from cars'

Solution 3 - Ruby on-Rails

To get a list of all model classes, you can use ActiveRecord::Base.subclasses e.g.

ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }

Solution 4 - Ruby on-Rails

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db. Both commands will direct you the command line interface and will allow you to use that database query syntax.

Solution 5 - Ruby on-Rails

Run this:

Rails.application.eager_load! 

Then

ActiveRecord::Base.descendants

To return a list of models/tables

Solution 6 - Ruby on-Rails

Its a start, it can list:

models = Dir.new("#{RAILS_ROOT}/app/models").entries

Looking some more...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrtfmincView Question on Stackoverflow
Solution 1 - Ruby on-RailscwninjaView Answer on Stackoverflow
Solution 2 - Ruby on-Railshamster hamView Answer on Stackoverflow
Solution 3 - Ruby on-RailsDomQView Answer on Stackoverflow
Solution 4 - Ruby on-RailsRalf Rafael FrixView Answer on Stackoverflow
Solution 5 - Ruby on-RailsstevecView Answer on Stackoverflow
Solution 6 - Ruby on-RailsrtfmincView Answer on Stackoverflow