198

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.

Flip
  • 6,233
  • 7
  • 46
  • 75
rtfminc
  • 6,243
  • 7
  • 36
  • 45
  • 2
    that's what script/dbconsole is for though – hgmnz Jan 20 '10 at 00:25
  • Yes, that drops you into mysql (or whatever). For some stranger reason I want to list columns/tables etc from regular console. I am thinking that it might require custom made ruby methods to do such a thing. – rtfminc Jan 20 '10 at 02:19

6 Answers6

401

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.

Jason Swett
  • 43,526
  • 67
  • 220
  • 351
cwninja
  • 9,550
  • 1
  • 29
  • 22
33

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'

hamster ham
  • 729
  • 8
  • 8
  • 11
    'rails dbconsole' puts you in the command line interpreter (CLI) of whatever database engine you're using... the above are SQLite commands... Postgres, for example, would use '\dt' to list tables... – Tom Hundt Jun 03 '16 at 21:21
  • is there a way to ensure that every time you don't have to apply .headers on and .more columns when running rails db – Mark Nov 06 '17 at 12:25
  • 1
    TIL. after 12 years, didn't know `rails db` is a thing. lul – Tim Kretschmer Oct 16 '21 at 09:55
9

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" }
DomQ
  • 4,184
  • 38
  • 37
4

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.

Mestica
  • 1,489
  • 4
  • 23
  • 33
1

Run this:

Rails.application.eager_load! 

Then

ActiveRecord::Base.descendants

To return a list of models/tables

stevec
  • 41,291
  • 27
  • 223
  • 311
-3

Its a start, it can list:

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

Looking some more...

JP Silvashy
  • 46,977
  • 48
  • 149
  • 227
rtfminc
  • 6,243
  • 7
  • 36
  • 45
  • 3
    by doing this you just list models files what if tables are exists in db and do not have model fild in the models dir !! – abo-elleef Oct 31 '13 at 05:58