Ruby on Rails
Updated: September 10, 2025Categories: Languages, Web, Frontend, Backend, Framework
Printed from:
Ruby on Rails Cheatsheet
1. Installation and Setup
Prerequisites
- Ruby (recommended version: 3.1+)
- RubyGems
- Bundler
Installation
Bash
123456789101112# Install Rails
gem install rails
# Create a new Rails project
rails new project_name
# Create a new Rails project with specific options
rails new project_name \
-d postgresql \
--skip-test \
--webpack=react
Ruby Version Management
Bash
12345678# Using RVM
rvm install 3.1.0
rvm use 3.1.0
# Using rbenv
rbenv install 3.1.0
rbenv global 3.1.0
2. Project Structure
my_rails_app/
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ ├── helpers/
│ ├── assets/
│ └── mailers/
├── config/
│ ├── routes.rb
│ ├── database.yml
│ └── application.rb
├── db/
│ └── migrate/
├── lib/
├── log/
├── public/
├── test/ or spec/
└── vendor/
3. Routing
Basic Routes
Ruby
12345678910111213141516171819# config/routes.rb
Rails.application.routes.draw do
# RESTful routes for a resource
resources :users
# Custom routes
get '/about', to: 'pages#about'
# Nested routes
resources :posts do
resources :comments
end
# Namespaced routes
namespace :admin do
resources :users
end
}
Route Helpers
Ruby
12345# Generated route helpers
users_path # => '/users'
new_user_path # => '/users/new'
edit_user_path(user) # => '/users/1/edit'
4. Controllers
Basic Controller
Ruby
1234567891011121314151617181920212223242526272829303132333435class UsersController < ApplicationController
# Filter/before action
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
@users = User.all
end
def show
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to @user, notice: 'User created!'
else
render :new
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :email)
end
end
Strong Parameters
Ruby
12345678def user_params
params.require(:user).permit(
:name,
:email,
addresses: [:street, :city]
)
end
5. Views
ERB Basics
erb
12345678910111213141516<%# Embedded Ruby (ERB) %> <h1>Welcome, <%= @user.name %></h1> <%# Conditional %> <% if @users.any? %> <ul> <% @users.each do |user| %> <li><%= user.name %></li> <% end %> </ul> <% end %> <%# Partials %> <%= render 'shared/header' %> <%= render partial: 'user', collection: @users %>
View Helpers
Ruby
12345# In view or helper
link_to 'Edit', edit_user_path(user)
image_tag 'logo.png'
number_to_currency(price)
6. Models
ActiveRecord Model
Ruby
1234567891011121314151617181920212223242526class User < ApplicationRecord
# Validations
validates :email,
presence: true,
uniqueness: true,
format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i }
# Associations
has_many :posts
belongs_to :organization, optional: true
# Scopes
scope :active, -> { where(active: true) }
scope :recent, ->(days) { where('created_at >= ?', days.days.ago) }
# Class method
def self.find_by_email(email)
find_by(email: email)
end
# Instance method
def full_name
"#{first_name} #{last_name}"
end
end
Query Methods
Ruby
12345678# Finding records
User.find(1) # Find by ID
User.find_by(email: 'x@y.com')# Find first matching record
User.where(active: true) # Find all matching records
User.order(created_at: :desc) # Ordered results
User.limit(10) # Limit results
User.includes(:posts) # Eager loading
7. Database Operations
Migrations
Bash
12345678# Generate migration
rails generate migration CreateUsers name:string email:string
# Run migrations
rails db:migrate
rails db:rollback
rails db:reset
Ruby
1234567891011# Migration example
class CreateUsers < ActiveRecord::Migration[6.1]
def change
create_table :users do |t|
t.string :name
t.string :email, index: { unique: true }
t.timestamps
end
end
end
Seeds
Ruby
12345678910# db/seeds.rb
5.times do
User.create!(
name: Faker::Name.name,
email: Faker::Internet.email
)
end
rails db:seed
8. Authentication & Authorization
Devise Gem (Basic Setup)
Ruby
12345678910# Gemfile
gem 'devise'
# Generate configuration
rails generate devise:install
rails generate devise User
# In application controller
before_action :authenticate_user!
Pundit for Authorization
Ruby
12345678910111213# Gemfile
gem 'pundit'
# Generate policy
rails generate pundit:policy User
# Example policy
class UserPolicy < ApplicationPolicy
def update?
user.admin? || record == user
end
end
9. Testing
RSpec Setup
Ruby
12345678910111213141516# Gemfile
group :development, :test do
gem 'rspec-rails'
end
# Generate specs
rails generate rspec:install
# Model spec example
RSpec.describe User, type: :model do
it "is valid with valid attributes" do
user = User.new(name: "John", email: "john@example.com")
expect(user).to be_valid
end
end
10. Common Commands
Bash
1234567891011121314151617# Rails Commands
rails new project_name
rails server # Start server
rails console # Interactive console
rails generate # Generate models, controllers
rails destroy # Remove generated resources
rails routes # List routes
rails dbconsole # Database console
# Bundler
bundle install # Install dependencies
bundle update # Update gems
# Testing
rails test
rspec # For RSpec
11. Configuration
Environment Configuration
Ruby
12345678910111213141516# config/environments/development.rb
Rails.application.configure do
config.cache_classes = false
config.active_record.verbose_query_logs = true
end
# config/application.rb
module MyApp
class Application < Rails::Application
config.time_zone = 'Eastern Time (US & Canada)'
config.generators do |g|
g.test_framework :rspec
end
end
end
12. Common Patterns and Best Practices
- Keep controllers skinny, models fat
- Use service objects for complex logic
- Implement thin views with helpers
- Use concerns for shared behavior
- Follow RESTful conventions
- Use background jobs for time-consuming tasks
- Implement caching strategies
- Use environment variables for configuration
13. Debugging and Troubleshooting
Ruby
123456789# Debugging
binding.pry # Breakpoint with Pry
Rails.logger.debug # Logging
# Common Issues
# - N+1 queries: Use includes, eager loading
# - Slow queries: Use database indexes
# - Memory leaks: Profile with tools like rack-mini-profiler
Recommended Gems
devise: Authenticationpundit: Authorizationsidekiq: Background jobsrspec-rails: Testingfactory_bot: Test data generationfaker: Fake data generationrubocop: Code style enforcementbullet: N+1 query detection
Pro Tips:
- Keep dependencies updated
- Monitor performance
- Write comprehensive tests
- Follow Ruby style guide
- Use environment-specific configurations
Continue Learning
Discover more cheatsheets to boost your productivity