Rails Database Console Cheat Sheet
Opening the SQL client of a Rails app's database, and the psql commands I use once inside.
Overview
bin/rails dbconsole (short form bin/rails db) reads config/database.yml and starts the matching client: psql for PostgreSQL, mysql for MySQL, sqlite3 for SQLite. It is the Rails counterpart of Django's manage.py dbshell.
Details
Opening the Console
| Command | Does |
|---|---|
bin/rails db |
connect to the development database (bundle exec rails db is equivalent) |
bin/rails db -e test |
connect to another environment's database |
bin/rails db -p |
pass the password from database.yml to the client, so it doesn't prompt |
psql Meta-Commands
| Command | Does |
|---|---|
\d |
list tables, views and sequences |
\dt |
list tables only |
\d <table> |
describe a table: columns, types, indexes |
\l |
list databases |
\x |
toggle expanded display, one column per line |
\q |
quit |
References
- Rails Guides: The Rails Command Line, bin/rails dbconsole - supported databases and options.
- PostgreSQL documentation: psql - the meta-commands.
Review cards
Flashcard What does the `-e` option in `bin/rails db -e <environment>` do?
It specifies the database environment to connect to, such as test or production.
Quiz Inside psql, which command lists only the tables of the current database?
- \dt
- \d
- \l
- \x
\d also lists views and sequences, \l lists databases, and \x toggles expanded output.