Skip
Arish's avatar

6. Essential Rails Commands


Essential Rails Commands

Rails provides powerful command-line tools that make development fast and efficient. Let's explore the most important commands you'll use daily.

Server Commands

Starting the Development Server

bash
1# Start the server on default port 3000
2rails server
3# Shorthand
4rails s
5
6# Start on a different port
7rails s -p 4000
8
9# Bind to all interfaces (useful in Docker)
10rails s -b 0.0.0.0

Rails Console

The console lets you interact with your application in real-time:

bash
1# Start the console
2rails console
3# Shorthand
4rails c
5
6# Start in sandbox mode (changes are rolled back)
7rails c --sandbox

Inside the console:

ruby
1# Create a record
2user = User.create(name: "John", email: "john@example.com")
3
4# Query records
5User.all
6User.find(1)
7User.where(active: true)
8
9# Update a record
10user.update(name: "Jane")
11
12# Delete a record
13user.destroy
14
15# Reload the console (after code changes)
16reload!

Generator Commands

Generators create boilerplate code for you:

Generate a Model

bash
1rails generate model Article title:string body:text published:boolean
2# Shorthand
3rails g model Article title:string body:text published:boolean

This creates:

  • app/models/article.rb - The model file
  • db/migrate/xxx_create_articles.rb - Database migration
  • test/models/article_test.rb - Test file

Generate a Controller

bash
1rails g controller Articles index show new create edit update destroy

This creates:

  • app/controllers/articles_controller.rb - Controller with actions
  • app/views/articles/ - View templates for each action
  • Routes (if using --skip-routes is not specified)
  • Helper and test files

Generate a Scaffold

Scaffolds generate a complete CRUD interface:

bash
1rails g scaffold Product name:string price:decimal description:text

This creates model, migration, controller, views, routes, and tests - everything for a complete CRUD feature!

Generate a Migration

bash
1# Create a new table
2rails g migration CreateProducts name:string price:decimal
3
4# Add a column to existing table
5rails g migration AddCategoryToProducts category:string
6
7# Add an index
8rails g migration AddIndexToProductsName
9
10# Remove a column
11rails g migration RemovePriceFromProducts price:decimal

Other Useful Generators

bash
1# Generate a mailer
2rails g mailer UserMailer welcome_email password_reset
3
4# Generate a job
5rails g job SendNewsletter
6
7# Generate a channel (Action Cable)
8rails g channel Notifications
9
10# See all available generators
11rails g --help

Database Commands

Creating and Managing Databases

bash
1# Create the database
2rails db:create
3
4# Drop the database
5rails db:drop
6
7# Run pending migrations
8rails db:migrate
9
10# Rollback the last migration
11rails db:rollback
12
13# Rollback multiple migrations
14rails db:rollback STEP=3
15
16# Check migration status
17rails db:migrate:status
18
19# Reset database (drop, create, migrate)
20rails db:reset
21
22# Seed the database
23rails db:seed
24
25# Setup database (create, migrate, seed)
26rails db:setup

Migration Shortcuts

bash
1# Migrate to a specific version
2rails db:migrate VERSION=20240101000000
3
4# Redo the last migration (rollback + migrate)
5rails db:migrate:redo

Route Commands

bash
1# Display all routes
2rails routes
3
4# Filter routes by controller
5rails routes -c articles
6
7# Filter routes by HTTP method
8rails routes -g POST
9
10# Show route for a specific path
11rails routes | grep users

Asset Commands

bash
1# Precompile assets for production
2rails assets:precompile
3
4# Clean old compiled assets
5rails assets:clean
6
7# Clobber (remove all compiled assets)
8rails assets:clobber

Testing Commands

bash
1# Run all tests
2rails test
3
4# Run specific test file
5rails test test/models/user_test.rb
6
7# Run specific test by line number
8rails test test/models/user_test.rb:15
9
10# Run system tests
11rails test:system

Rake Tasks

bash
1# List all available tasks
2rails -T
3
4# List tasks matching a pattern
5rails -T db
6
7# Create a custom task
8rails g task my_namespace my_task

Custom rake task example:

ruby
1# lib/tasks/maintenance.rake
2namespace :maintenance do
3  desc "Clean up old records"
4  task cleanup: :environment do
5    puts "Cleaning up old records..."
6    Article.where('created_at < ?', 1.year.ago).destroy_all
7    puts "Done!"
8  end
9end
10
11# Run with: rails maintenance:cleanup

Destroying Generated Files

Undo any generator command with destroy:

bash
1rails destroy model Article
2rails destroy controller Articles
3rails destroy scaffold Product
4# Shorthand
5rails d model Article

Credentials Commands

bash
1# Edit credentials (opens in editor)
2rails credentials:edit
3
4# Edit environment-specific credentials
5rails credentials:edit --environment production
6
7# Show credential value
8rails credentials:show

Quick Reference Card

bash
1# Development
2rails s                    # Start server
3rails c                    # Console
4rails routes               # Show routes
5
6# Generators
7rails g model Name         # Generate model
8rails g controller Name    # Generate controller
9rails g scaffold Name      # Generate scaffold
10rails g migration Name     # Generate migration
11
12# Database
13rails db:create            # Create database
14rails db:migrate           # Run migrations
15rails db:rollback          # Undo last migration
16rails db:seed              # Seed data
17rails db:reset             # Reset database
18
19# Testing
20rails test                 # Run tests
21
22# Cleanup
23rails d model Name         # Destroy generated files

Master these commands, and you'll be navigating Rails like a pro!