Ruby on Rails Cheat Sheet: The Complete Reference Guide
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
-
Ruby on Rails Official Guides — Getting Started - Official Rails getting started guide covering project generation, MVC architecture, and CLI commands. ↩
-
Ruby on Rails Routing Guide - Comprehensive reference for Rails RESTful routing, resource definitions, and path helpers. ↩
-
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:
Footnotes
-
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)
- 1Step 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. - 2Step 2
Execute
rails db:migrateto apply the generated migration to the database schema. This creates thepoststable with the specified columns plusid,created_at, andupdated_attimestamps. - 3Step 3
Run
rails routesand confirm you see the 7 standard RESTful routes:index,show,new,create,edit,update,destroymapped under/posts. - 4Step 4
Open
app/models/post.rband add validations likevalidates :title, presence: true, length: { minimum: 5 }to enforce data integrity at the model level. - 5Step 5
If Post
has_many :comments, add the association and runrails g model Comment body:text post:referencesfollowed byrails db:migrate. - 6Step 6
Populate
db/seeds.rbwith sample records usingPost.create!(title: "Hello", body: "World", published: true)then runrails 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:
| Helper | Returns |
|---|---|
posts_path | /posts |
new_post_path | /posts/new |
edit_post_path(@post) | /posts/:id/edit |
post_path(@post) | /posts/:id |
Footnotes
-
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
-
Ruby on Rails Active Record Migrations Guide - Detailed documentation on migration DSL, reversible changes, and schema management. ↩
Rails Request Lifecycle
Browser → Router
1The browser sends an HTTP request. Rails parses the URL and matches it against routes defined in config/routes.rb."
Router → Middleware
2The request passes through the middleware stack (e.g., CSRF protection, session, cookies, Warden/Devise)."
Middleware → Controller
3Middleware processes and the request is dispatched to the corresponding controller action via before_action filters."
Controller → Model
4The controller interacts with Active Record models to query or persist data in the database."
Model → Controller
5Models return data (or raise errors). Callbacks fire on create/update/destroy operations."
Controller → View
6The controller renders a view template (ERB), passing instance variables (@posts, @post)."
View → Browser
7The 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
-
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 :
| Setting | Development | Test | Production |
|---|---|---|---|
config.cache_classes | false | true | true |
config.eager_load | false | false | true |
config.consider_all_requests_local | true | true | false |
config.action_controller.perform_caching | false | true | true |
config.active_record.migration_error | :raise | — | — |
config.log_level | :debug | :debug | :info |
Key config files:
config/application.rb— shared config across all environmentsconfig/environments/development.rb— dev-specific overridesconfig/database.yml— DB connection per environmentconfig/puma.rb— web server (Puma) configurationconfig/storage.yml— Active Storage service definitions
Footnotes
-
Ruby on Rails Official Guides — Getting Started - Official Rails getting started guide covering project generation, MVC architecture, and CLI commands. ↩
Rails Cheat Sheet Flashcards
Essential Gems Quick Reference
| Gem | Purpose | Common Config |
|---|---|---|
| Devise | Authentication | rails generate devise:install then devise :users |
| Pundit | Authorization | Define app/policies/ classes with def index? etc. |
| [Cancancan] | Authorization | ability.rb with can :read, Post |
| [Kaminari] | Pagination | Post.page(1).per(25) |
| [Pagy] | Pagination (faster) | @pagy, @posts = pagy(Post.all) |
| [Rspec-rails] | Testing | rails generate rspec:install |
| [Factory Bot] | Test data | FactoryBot.create(:post) |
| [Bullet] | N+1 detection | Auto-warns in development |
| Sidekiq | Background jobs | include Sidekiq::Worker + perform_async |
| [AASM] | State machines | include AASM + aasm column: :status |
| [Annotate] | Schema comments | rails 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
Which Rails command generates a full RESTful resource with model, views, and controller?
Explore Related Topics
React: A Comprehensive Guide to Modern UI Development
Blockchain Developer Skills: A Comprehensive Guide
This comprehensive guide maps the roadmap, skills, and resources required to become a competent blockchain developer.
- Core skill tree spans computer science fundamentals, blockchain theory, smart contract coding, DApp front‑end, and security auditing.
- Primary programming languages are Solidity (≈90% of contracts) and Rust (gaining traction for high‑performance chains).
- Understanding consensus (PoW, PoS, DPoS, PoH) and tokenomics is vital for protocol design.
- Smart contract security is critical, with total DeFi hacks (2021‑2024) highlighting the risk.
- Market demand is soaring (942 B by 2032) and salaries range from 500k+ senior roles.
Retrieval-Augmented Generation (RAG): A Comprehensive Course