Ruby on Rails Cheat Sheet: The Complete Reference Guide

Ruby on Rails Cheat Sheet: The Complete Reference Guide

Verified Sources
Jun 19, 2026

Ruby on Rails (often simply "Rails") is a server-side MVC framework written in Ruby. It emphasizes convention over configuration and the DRY principle, making it one of the most productive web development frameworks available 2.

Rails follows a RESTful architecture by default, and ships with everything needed to build database-backed web applications: an ORM (Active Record), a routing system, a view template engine, and a powerful CLI.

Whether you're a beginner ramping up or a veteran needing a quick reference, this cheat sheet covers the most essential Rails commands, patterns, and APIs you'll reach for daily .

Footnotes

  1. Ruby on Rails Official Guides — Getting Started - Official Rails getting started guide covering project generation, MVC architecture, and CLI commands.

  2. Ruby on Rails Routing Guide - Comprehensive reference for Rails RESTful routing, resource definitions, and path helpers.

  3. Ruby on Rails Active Record Migrations Guide - Detailed documentation on migration DSL, reversible changes, and schema management.

Ruby on Rails — Best Tips & Tricks

Rails CLI Commands

The rails command is your Swiss Army knife. Below is the definitive quick-reference table for the most-used CLI commands:

CommandDescription
rails new app_nameGenerate a new Rails application
rails server / rails sStart the development server (port 3000)
rails console / rails cOpen an interactive Ruby session with Rails loaded
rails generate / rails gRun a generator (scaffold, model, controller, etc.)
rails db:migrateRun pending migrations
rails db:rollbackRoll back the last migration
rails db:seedLoad seed data from db/seeds.rb
rails db:drop db:create db:migrateFull database reset
rails routesList all defined routes
rails test / rails tRun the test suite
rails statsShow code statistics (KLOCs, etc.)
rails aboutShow Rails, Ruby, and gem version info
rails middlewareList middleware stack
rails zeitwerk:checkVerify project autoloading configuration

Footnotes

  1. Ruby on Rails Official Guides — Getting Started - Official Rails getting started guide covering project generation, MVC architecture, and CLI commands.

Rails Generator Types & Popularity

Most frequently used rails generate sub-commands by developer usage

Creating a Complete Rails Resource (Scaffold Workflow)

  1. 1
    Step 1

    Run rails g scaffold Post title:string body:text published:boolean. This creates the model, migration, controller with all 7 RESTful actions, views, and route.

  2. 2
    Step 2

    Execute rails db:migrate to apply the generated migration to the database schema. This creates the posts table with the specified columns plus id, created_at, and updated_at timestamps.

  3. 3
    Step 3

    Run rails routes and confirm you see the 7 standard RESTful routes: index, show, new, create, edit, update, destroy mapped under /posts.

  4. 4
    Step 4

    Open app/models/post.rb and add validations like validates :title, presence: true, length: { minimum: 5 } to enforce data integrity at the model level.

  5. 5
    Step 5

    If Post has_many :comments, add the association and run rails g model Comment body:text post:references followed by rails db:migrate.

  6. 6
    Step 6

    Populate db/seeds.rb with sample records using Post.create!(title: "Hello", body: "World", published: true) then run rails db:seed.

Routing Essentials

Routes are defined in config/routes.rb. Rails defaults to RESTful routing, which means every [resource]{def="A RESTful entity mapped to CRUD via HTTP verbs: GET, POST, PUT/PATCH, DELETE} gets a standard set of routes .

1# config/routes.rb 2 3# Full RESTful resource — creates 7 routes automatically 4resources :posts 5 6# Nested resource 7resources :posts do 8 resources :comments 9end 10 11# Only/Except — limit generated routes 12resources :articles, only: [:index, :show] 13resources :admin, except: [:destroy] 14 15# Singular resource (no :id in URL) 16resource :profile 17 18# Custom member and collection routes 19resources :posts do 20 member do 21 post :publish # POST /posts/:id/publish 22 end 23 collection do 24 get :search # GET /posts/search 25 end 26end 27 28# Non-RESTful routes 29get '/about', to: 'pages#about' 30root 'home#index'

Named Route Helpers generated by resources :posts:

HelperReturns
posts_path/posts
new_post_path/posts/new
edit_post_path(@post)/posts/:id/edit
post_path(@post)/posts/:id

Footnotes

  1. Ruby on Rails Routing Guide - Comprehensive reference for Rails RESTful routing, resource definitions, and path helpers.

Querying:

1Post.all 2Post.first / Post.last 3Post.find(1) 4Post.find_by(title: "Hello") 5Post.where(published: true) 6Post.order(created_at: :desc) 7Post.limit(10).offset(20) 8Post.count / Post.pluck(:title) 9 10# Scopes 11scope :published, -> { where(published: true) } 12 13# Callbacks 14before_save :normalize_title 15after_create :send_welcome_email 16after_destroy :log_deletion

Migrations Deep Dive

Migrations are the cornerstone of Rails' database management. They provide a reversible, versioned way to evolve your schema .

1# Creating a table 2class CreatePosts < ActiveRecord::Migration[7.1] 3 def change 4 create_table :posts do |t| 5 t.string :title, null: false 6 t.text :body 7 t.boolean :published, default: false 8 t.integer :view_count, default: 0 9 t.decimal :price, precision: 8, scale: 2 10 t.date :published_on 11 t.datetime :published_at 12 t.references :user, foreign_key: true 13 t.timestamps # adds created_at, updated_at 14 end 15 16 add_index :posts, :title, unique: true 17 add_index :posts, [:user_id, :published] 18 end 19end 20 21# Adding columns (reversible) 22class AddEmailToUsers < ActiveRecord::Migration[7.1] 23 def change 24 add_column :users, :email, :string 25 add_index :users, :email, unique: true 26 end 27end 28 29# Irreversible migration — requires up/down 30class RemoveLegacyData < ActiveRecord::Migration[7.1] 31 def up 32 remove_column :users, :legacy_field 33 end 34 35 def down 36 add_column :users, :legacy_field, :string 37 end 38end

Legacy migration versioning: Use ActiveRecord::Migration[7.1] (where 7.1 is your Rails version).

Footnotes

  1. Ruby on Rails Active Record Migrations Guide - Detailed documentation on migration DSL, reversible changes, and schema management.

1class Post < ApplicationRecord 2 # Presence 3 validates :title, presence: true 4 5 # Uniqueness 6 validates :slug, uniqueness: true 7 8 # Length 9 validates :body, length: { minimum: 10, maximum: 5000 } 10 11 # Format 12 validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } 13 14 # Inclusion / Exclusion 15 validates :status, inclusion: { in: %w[draft published archived] } 16 validates :role, exclusion: { in: %w[admin superadmin] } 17 18 # Numericality 19 validates :price, numericality: { greater_than: 0 } 20 21 # Custom validation 22 validate :publication_date_cannot_be_future 23 24 private 25 def publication_date_cannot_be_future 26 return unless published_at.present? && published_at > Date.today 27 errors.add(:published_at, "can't be in the future") 28 end 29end

Rails Request Lifecycle

Browser → Router

1

The browser sends an HTTP request. Rails parses the URL and matches it against routes defined in config/routes.rb."

Router → Middleware

2

The request passes through the middleware stack (e.g., CSRF protection, session, cookies, Warden/Devise)."

Middleware → Controller

3

Middleware processes and the request is dispatched to the corresponding controller action via before_action filters."

Controller → Model

4

The controller interacts with Active Record models to query or persist data in the database."

Model → Controller

5

Models return data (or raise errors). Callbacks fire on create/update/destroy operations."

Controller → View

6

The controller renders a view template (ERB), passing instance variables (@posts, @post)."

View → Browser

7

The rendered HTML/JSON response travels back through middleware to the browser."

Rails Console Power Tips

The Rails console is one of the most powerful tools in a Rails developer's arsenal .

1# Start console in specific environment 2rails c -e production 3rails c --sandbox # all changes rolled back on exit 4 5# Sandbox mode — safe experimentation 6# Every DB change is rolled back when you exit 7 8# Helper methods available in console 9app.posts_path # => "/posts" 10app.post_path(1) # => "/posts/1" 11helper.number_to_currency(29.99) # => "$29.99" 12 13# Query tricks 14Post.pluck(:title) # => ["Hello", "World"] (faster than .map) 15Post.insert_all(rows) # Bulk insert (no callbacks/timestamps) 16Post.upsert_all(rows) # Insert or update 17Post.find_or_create_by(title: "First") 18Post.find_or_initialize_by(title: "First") 19 20# Reload schema 21ActiveRecord::Base.connection.schema_cache.clear! 22ActiveRecord::Migration.run(:up, 20240101000000) 23 24# Get SQL for a query 25Post.where(published: true).to_sql 26 27# Explain a query plan 28Post.where(published: true).explain

Footnotes

  1. Ruby on Rails Command Line Guide - Reference for the Rails CLI including console tips, generators, and Rake tasks.

Rails Advanced Topics & Edge Cases

N+1 Query Warning

Always watch for N+1 queries in your views! If you iterate over @posts and call post.user.name for each, Rails fires one query per post. Fix it with Post.includes(:user) or use the Bullet gem to detect N+1 queries automatically in development.

Pro Tip: Use `.pluck` Instead of `.map`

When you only need specific column values, Post.pluck(:title) is significantly faster than Post.all.map(&:title) because it doesn't instantiate Active Record objects — it returns raw values directly from the database driver.

Rails Environment Configuration

Rails ships with three standard environments — each with distinct caching, logging, and error behavior :

SettingDevelopmentTestProduction
config.cache_classesfalsetruetrue
config.eager_loadfalsefalsetrue
config.consider_all_requests_localtruetruefalse
config.action_controller.perform_cachingfalsetruetrue
config.active_record.migration_error:raise
config.log_level:debug:debug:info

Key config files:

  • config/application.rb — shared config across all environments
  • config/environments/development.rb — dev-specific overrides
  • config/database.yml — DB connection per environment
  • config/puma.rb — web server (Puma) configuration
  • config/storage.yml — Active Storage service definitions

Footnotes

  1. Ruby on Rails Official Guides — Getting Started - Official Rails getting started guide covering project generation, MVC architecture, and CLI commands.

Rails Cheat Sheet Flashcards

1 / 8
13%
Question · Term

What command starts the Rails console?

Click to reveal
Answer · Definition

rails console or rails c. Append -e production for production or --sandbox for auto-rollback.

Essential Gems Quick Reference

GemPurposeCommon Config
DeviseAuthenticationrails generate devise:install then devise :users
PunditAuthorizationDefine app/policies/ classes with def index? etc.
[Cancancan]Authorizationability.rb with can :read, Post
[Kaminari]PaginationPost.page(1).per(25)
[Pagy]Pagination (faster)@pagy, @posts = pagy(Post.all)
[Rspec-rails]Testingrails generate rspec:install
[Factory Bot]Test dataFactoryBot.create(:post)
[Bullet]N+1 detectionAuto-warns in development
SidekiqBackground jobsinclude Sidekiq::Worker + perform_async
[AASM]State machinesinclude AASM + aasm column: :status
[Annotate]Schema commentsrails g annotate:install

Never Skip Strong Parameters!

If you accidentally pass params directly to .create or .update, you expose your app to mass-assignment vulnerabilities. Always use params.require(:model).permit(:field1, :field2) to whitelist only the attributes that should be modifiable. Rails will raise an ActiveModel::ForbiddenAttributesError if you forget.

Common Rails Rake Tasks & Shortcuts

1# Database tasks 2rails db:create # Create database from config/database.yml 3rails db:drop # Drop the database 4rails db:migrate # Run pending migrations 5rails db:migrate:status # Show migration status 6rails db:rollback # Roll back last migration (or STEP=3) 7rails db:seed # Run db/seeds.rb 8rails db:schema:load # Load schema.rb (faster than running all migrations) 9rails db:reset # db:drop + db:create + db:schema:load + db:seed 10 11# Rerun all migrations from scratch 12rails db:migrate:redo # rollback + migrate again 13 14# Clear logs 15rails log:clear # Truncates all log files to zero 16 17# Show current routes with grep 18rails routes | grep posts 19rails routes -g post #等效grep

Knowledge Check

Question 1 of 5
Q1Single choice

Which Rails command generates a full RESTful resource with model, views, and controller?

Explore Related Topics

1

Cloud Engineer Roadmap: From Beginner to Expert

Cloud engineering has emerged as one of the most impactful and in-demand careers in modern technology. As organizations continue migrating infrastructure to the cloud—at unprecedented scale—skilled cloud engineers are the architects and operators making it all possible. The public cloud computing ma

2

Pass Coding Interviews: A Comprehensive Strategy Guide

A data‑driven, pattern‑based guide that covers foundational DS&A, the highest‑ROI algorithm patterns, a 6‑step coding interview framework, and behavioral STAR preparation.

  • Recognize and master top patterns—DFS/BFS (~22%), Two Pointers (~16%), Sliding Window (~12%), Binary Search (~11%), Hash Map (~10%)—to cover most interview problems.
  • Apply the 6‑step process: Clarify → Work examples → Brainstorm (state O()O(\dots)) → Implement → Test/Debug → Optimize & discuss trade‑offs.
  • Follow a 9‑week roadmap: foundation, pattern recognition, advanced patterns, mock interviews, then real interview execution, targeting ~150 curated problems.
  • Use the STAR method (20‑10‑60‑10 split) with a story bank; be honest, use “I” statements, and choose the language you’re most fluent in.
3

CSS Flexbox Cheat Sheet: The Complete Reference Guide

CSS Flexbox is a one‑dimensional layout model that uses a main axis (set by flex-direction) and a cross axis to control distribution and alignment of flex items within a container.

  • justify-content aligns items along the main axis, while align-items and align-content work on the cross axis (the latter only with wrapped lines).
  • Container properties (display, flex-direction, flex-wrap, justify-content, align-items, align-content, gap) manage group distribution; item properties (order, flex-grow, flex-shrink, flex-basis, flex, align-self) control individual behavior.
  • The flex shorthand (e.g., flex: 1, flex: none) combines grow, shrink, and basis; extra space is allocated by Item size=flex-basis+flex-growiflex-grow×free space\text{Item size} = \text{flex-basis} + \frac{\text{flex-grow}_i}{\sum \text{flex-grow}} \times \text{free space} and overflow is resolved by Shrink amounti=flex-shrinki×flex-basisi(flex-shrink×flex-basis)×overflow\text{Shrink amount}_i = \frac{\text{flex-shrink}_i \times \text{flex-basis}_i}{\sum (\text{flex-shrink} \times \text{flex-basis})} \times \text{overflow}.
  • Common patterns include perfect centering, navbar push‑right via margin-left:auto, Holy Grail layout, responsive card grids with gap, and sticky footers using column direction.
  • Beware of pitfalls: align-content has no effect on single‑line containers, and the default min-width:auto can prevent shrinking, requiring min-width:0 to avoid overflow.