Rails cheat sheet
Generators
Section titled “Generators”rails new my_app --database=postgresqlrails generate model Post title:string body:text published_at:datetimerails generate controller Posts index showrails generate migration AddSlugToPosts slug:string:uniqrails generate job PublishPostrails destroy model PostMigrations
Section titled “Migrations”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 endendadd_column :posts, :slug, :stringremove_column :posts, :legacy, :stringadd_index :posts, :slug, unique: trueadd_reference :comments, :post, foreign_key: true
# Large tables: do not lock writesdisable_ddl_transaction!add_index :posts, :slug, algorithm: :concurrentlyrails db:migraterails db:rollback STEP=2rails db:migrate:statusrails db:seedrails db:resetActiveRecord
Section titled “ActiveRecord”Post.allPost.find(1)Post.find_by(slug: "hello")Post.where(published: true).order(created_at: :desc).limit(10)Post.where(created_at: 1.week.ago..).countPost.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 }endRoutes
Section titled “Routes”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"endrails routesrails routes -g postControllers
Section titled “Controllers”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) endendTesting
Section titled “Testing”bin/rails testbin/rails test test/models/post_test.rbbundle exec rspecbundle exec rspec spec/models/post_spec.rb:42RSpec.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) endendConsole and debugging
Section titled “Console and debugging”bin/rails consolebin/rails console --sandboxbin/rails runner "puts Post.count"tail -f log/development.logapp.get "/posts"post = Post.firstpost.attributespost.errors.full_messagesActiveRecord::Base.logger = Logger.new($stdout)Performance checklist
Section titled “Performance checklist”- 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_eachfor large batches. - Watch for callbacks that trigger extra queries.
Security checklist
Section titled “Security checklist”- Strong parameters for every write.
protect_from_forgeryis on by default; do not disable it.- Escape output by default; avoid
html_safeon user input. - Use credentials or environment variables for secrets.
- Set
Secure,HttpOnlyandSameSiteon session cookies. - Run Brakeman and
bundle auditin CI.