rails-query
rails-query
rails query is a Rails 8.2+ command for running read-only queries against the database. Input is a single expression, output is a single JSON object on stdout ({columns, rows, meta}; errors go to stderr with non-zero exit), and writes are blocked at the connection level. With a read replica configured it hits the replica automatically, so it's safe to point at production.
Prefer it over a console, a script, or SSH for any data question. One invocation, structured output, nothing to clean up.
The flow
1. Know where you're running
- Local (
bin/rails query) — development, tests, or anywhere you have the app checked out. - Remote via Kamal (
bin/kamal query -d <destination>) — when the app is deployed with Kamal. Requires a small alias inconfig/deploy.yml(see "Kamal setup").
If you don't know whether Kamal is configured, check config/deploy.yml for an aliases: block.
2. Decide: Ruby expression or raw SQL
Default: Ruby (ActiveRecord). The expression is eval'd in the app context — scopes, associations, finders, aggregates all work. Model logic (encryption, default scopes, polymorphism) is honored.