Ruby on Rails
Ruby on Rails cheat sheet with MVC architecture, Active Record, routing, migrations, controllers, and deployment code examples.
Setup
Install Ruby and Rails, verify both versions, and create an application.
Install Ruby with Mise, add Rails, and generate a new application.
# Install Mise, activate it, then install Ruby 3
curl https://mise.run | sh
eval "$(~/.local/bin/mise activate bash)"
mise use -g ruby@3
# Install and verify Rails
gem install rails
ruby --version
rails --versionGetting Started
Create a new Rails application with various options
# Basic app
rails new myapp
# API-only app
rails new myapp --api
# Skip specific components
rails new myapp --skip-test --skip-bundleStart development server and interactive console
# Start development server
rails server
# or shorthand
rails s
# Specify port
rails s -p 3001
# Rails console
rails console
rails cGenerators
Generate models with migrations and attributes
# Basic model
rails generate model User name:string email:string
# Model with references
rails generate model Post title:string body:text user:references
# Model with indexes
rails generate model Product name:string:index price:decimalGenerate controllers with actions and views
# Controller with actions
rails generate controller Users index show new create
# API controller
rails generate controller api/v1/Posts index show --skip-template-engine
# Empty controller
rails generate controller AdminGenerate complete CRUD resource with all components
# Full scaffold
rails generate scaffold Post title:string body:text published:boolean
# API scaffold
rails generate scaffold_controller api/v1/Article \
title:string body:text \
--apiGenerate standalone database migrations
# Add column migration
rails generate migration AddEmailToUsers email:string
# Remove column migration
rails generate migration RemoveEmailFromUsers email:string
# Create join table
rails generate migration CreateJoinTableUserProject user projectDatabase & Migrations
Create, migrate, and manage database
# Create database
rails db:create
# Run migrations
rails db:migrate
# Rollback last migration
rails db:rollback
# Drop database
rails db:dropCommon methods used in migration files
class CreateProducts < ActiveRecord::Migration[7.0]
def change
create_table :products do |t|
t.string :name
t.text :description
t.decimal :price, precision: 8, scale: 2
t.integer :stock, default: 0
t.references :category, foreign_key: true
t.timestamps
end
add_index :products, :name
end
endRoutes
RESTful routes with resources
# Full CRUD routes
resources :posts
# Limit to specific actions
resources :posts, only: [:index, :show]
resources :posts, except: [:destroy]
# Nested resources
resources :users do
resources :posts
endDefine custom routes and root
# Root route
root 'posts#index'
# Simple route
get 'about', to: 'pages#about'
# Route with dynamic segments
get 'posts/:id', to: 'posts#show'
# Named routes
get 'dashboard', to: 'dashboard#index', as: :user_dashboardControllers
Common controller patterns and responses
class PostsController < ApplicationController
def index
@posts = Post.all
render json: @posts
end
def show
@post = Post.find(params[:id])
render :show
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Created!'
else
render :new, status: :unprocessable_entity
end
end
endBefore/after/around filters for controller actions
class ApplicationController < ActionController::Base
before_action :authenticate_user!
before_action :set_locale
after_action :log_action
around_action :catch_errors
private
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
endModels & Active Record
Define relationships between models
class User < ApplicationRecord
has_many :posts
has_one :profile
end
class Post < ApplicationRecord
belongs_to :user
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
endValidate model data before saving
class User < ApplicationRecord
validates :email, presence: true, uniqueness: true
validates :name, presence: true, length: { minimum: 2 }
validates :age, numericality: { greater_than: 18 }
endQuery database with Active Record
# Find records
Post.find(1)
Post.find_by(title: 'Hello')
Post.where(published: true)
Post.all
# Chain queries
Post.where(published: true).order(created_at: :desc).limit(10)Lifecycle hooks for model operations
class Post < ApplicationRecord
before_validation :normalize_title
before_save :generate_slug
after_create :send_notification
after_destroy :cleanup_files
private
def normalize_title
self.title = title.strip.titleize
end
end