What is Rails Console and How to Use?
Coming from Python or Node, you probably have your REPL habits — node, python3, ipython. Rails console is the equivalent, but it loads your entire Rails app environment: models, database connections, configs...
What Is Rails Console?
Rails console is an interactive IRB (Interactive Ruby) session with your full application loaded. That means you can call your models, run queries, test methods, and inspect data. All without touching the browser or writing a single use script.
# Start the console
bin/rails console
# Shorthand
bin/rails c
Once it's running, you'll see a prompt like:
my-app(dev):001>
The dev tells you which environment you're in. By default, it's development.
Starting Options
# Sandbox mode — all DB changes roll back on exit
bin/rails console --sandbox
# Start in a specific environment
bin/rails console -e staging
bin/rails console -e production
Sandbox mode is when you want to test destructive queries without worrying about accidentally affecting real data. Think of it as a dry-run mode.
Common Commands
Query Records
# Find by primary key
User.find(1)
# Find by any attribute
User.find_by(email: "[email protected]")
# Filter with conditions
User.where(role: "admin").limit(5)
# Count records
Order.where(status: "pending").count
Create, Update, Delete
# Create a record
User.create!(name: "Darren", email: "[email protected]")
# Update
user = User.find(1)
user.update!(role: "admin")
# Soft check — won't raise an error if validation fails
user.update(email: "") # returns false
user.update!(email: "") # raises ActiveRecord::RecordInvalid
# Delete
User.find(42).destroy
Inspect Model Attributes
user = User.last
user.attributes # returns a hash of all attributes
user.class # => User
user.class.column_names # see all DB columns for this model
Check File Content and verify file state
# Read a file (e.g., check a config template)
puts File.read(Rails.root.join("config", "database.yml"))
# Check when a file was last modified
puts File.mtime(Rails.root.join("db", "schema.rb"))
Rails.root.join supports two formats and both produce the same path:
# Comma separated segments
Rails.root.join("app", "services", "payment_service.rb")
# Slash separated path
Rails.root.join("app/services/payment_service.rb")
Check App Routes and Environment
# Current environment
Rails.env # => "development"
Rails.env.production? # => false
# Access named route helpers
app.root_path # => "/"
app.users_path # => "/users"
Reload Code Without Restarting
After editing a model or service file, make sure to run this command to see your changes reflected in the console. Otherwise, you'll be working with the old code.
reload!
Quick Tips
_(underscore) stores the result of the last expressionexitor Ctrl+D to quit- Ctrl+L to clear the screen
- Use
ppinstead ofputsfor pretty-printing nested hashes or arrays
pp User.last.attributes