Skip to content

Rails cheat sheet

Terminal window
rails new my_app --database=postgresql
rails generate model Post title:string body:text published_at:datetime
rails generate controller Posts index show
rails generate migration AddSlugToPosts slug:string:uniq
rails generate job PublishPost
rails destroy model Post
class CreatePosts < ActiveRecord::Migration[8.0]
def change
create_table :posts do |t|
t.string :title, null: false
t.text :body
t.references :user, null: false, foreign_key: true
t.timestamps
end
add_index :posts, :title
end
end
add_column :posts, :slug, :string
remove_column :posts, :legacy, :string
add_index :posts, :slug, unique: true
add_reference :comments, :post, foreign_key: true
# Large tables: do not lock writes
disable_ddl_transaction!
add_index :posts, :slug, algorithm: :concurrently
Terminal window
rails db:migrate
rails db:rollback STEP=2
rails db:migrate:status
rails db:seed
rails db:reset
Post.all
Post.find(1)
Post.find_by(slug: "hello")
Post.where(published: true).order(created_at: :desc).limit(10)
Post.where(created_at: 1.week.ago..).count
Post.includes(:user, :comments).where(users: { active: true })
Post.joins(:comments).group("posts.id").having("count(comments.id) > ?", 5)
Post.select(:id, :title).find_each { |post| ... }
Post.transaction { ... }
Post.lock.find(1)
Association Use
belongs_to :user The foreign key is on this model
has_one :profile The foreign key is on the other model
has_many :comments One-to-many
has_many :tags, through: :taggings Many-to-many
has_many :comments, as: :commentable Polymorphic
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_many :taggings
has_many :tags, through: :taggings
validates :title, presence: true, length: { maximum: 120 }
scope :published, -> { where.not(published_at: nil) }
before_save { self.slug = title.parameterize }
end
Rails.application.routes.draw do
root "home#index"
resources :posts do
resources :comments, only: [:create, :destroy]
end
namespace :api do
namespace :v1 do
resources :posts, only: [:index, :show]
end
end
get "health", to: "health#show"
end
Terminal window
rails routes
rails routes -g post
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.includes(:user).order(created_at: :desc)
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: "Post created."
else
render :new, status: :unprocessable_entity
end
end
private
def set_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body)
end
end
Terminal window
bin/rails test
bin/rails test test/models/post_test.rb
bundle exec rspec
bundle exec rspec spec/models/post_spec.rb:42
RSpec.describe Post, type: :model do
it "requires a title" do
expect(Post.new).not_to be_valid
end
it "eager loads comments" do
expect { Post.includes(:comments).to_a }.to make_database_queries(count: 2)
end
end
Terminal window
bin/rails console
bin/rails console --sandbox
bin/rails runner "puts Post.count"
tail -f log/development.log
app.get "/posts"
post = Post.first
post.attributes
post.errors.full_messages
ActiveRecord::Base.logger = Logger.new($stdout)
  • Eager load associations with includes / preload / eager_load.
  • Index every foreign key and every column used in where/order.
  • Paginate lists; never render an unbounded collection.
  • Move slow work to a background job.
  • Cache fragments or query results with a clear expiry.
  • Use find_each for large batches.
  • Watch for callbacks that trigger extra queries.
  • Strong parameters for every write.
  • protect_from_forgery is on by default; do not disable it.
  • Escape output by default; avoid html_safe on user input.
  • Use credentials or environment variables for secrets.
  • Set Secure, HttpOnly and SameSite on session cookies.
  • Run Brakeman and bundle audit in CI.