Blog
WebsiteLoginFree Trial
  • 🏠PagerTree Blog
  • πŸ“£Meet the PagerTree CLI: Your New On-Call Sidekick!
  • πŸ“£OpsGenie Shutdown Announced: Why PagerTree Is Your Best Alternative in 2025
  • πŸ’ŽGetting Started With Ruby on Rails in 2024 - The Complete Development Environment Guide
  • πŸ“£WhatsApp Notifications
  • 🧠Site Reliability Engineer (SRE) Interview Questions
  • πŸ‘‘What is System Monitoring?
  • πŸ‘‘Top 5 Best PagerDuty Alternatives in 2024
  • πŸ”‘Understanding Linux File System: A Comprehensive Guide to Common Directories
  • πŸ”‘Ping Command: A Comprehensive Guide to Network Connectivity Tests
  • πŸ“œFly.io migrate-to-v2 Postgres stuck in read-only mode
  • πŸ’ŽMulti-Tenant SSO using Devise
  • ✨PromQL Cheat Sheet: A Quick Guide to Prometheus Query Language
  • πŸ”‘PowerShell Cheat Sheet: Essential Commands for Efficient Scripting
  • πŸ“£Critical Alerts for iOS and iPhone
  • πŸ“£PagerTree 4.0 is finally here!
  • πŸ’ŽRuby on Rails Polymorphic Select Dropdown
  • 🧠SRE Metrics: Availability
  • 🚨Incident Response Alert Routing
  • πŸ’ŽRuby on Rails Development Setup for Beginners
  • ✨Jekyll site to AWS S3 using GitHub Actions
  • πŸ’ŽMigrate attr_encrypted to Rails 7 Active Record encrypts
  • πŸ’ŽRuby on Rails Cheat Sheet
  • πŸ“£PagerTree Forms Integration
  • πŸ“£Public Team Calendars
  • πŸ“£Slack, Mattermost, Microsoft Teams, and Google Chat
  • πŸ“£On-call Schedule Rotations
  • πŸ“£Maintenance Windows
  • ✨Docker Commands Cheat Sheet
  • πŸͺ„Slack Channel Stakeholder Notifications
  • πŸ“£PagerTree Live Call Routing
  • 🧠The Science of On-Call
  • ✨serverless
    • 🧠What is Serverless?
    • 🧠Serverless Scales
    • 🧠Serverless Costs
    • ✨Serverless Tools and Best Practices
  • ✨Prometheus Monitoring Tutorial
Powered by GitBook
On this page
  • Ruby Syntax
  • Hashes
  • Safe Navigation Operator
  • ERB
  • Rails commands
  • Rake Commands
  • Rails Framework
  • Migration Data Types
  • Controller Filters
  • Models Callbacks
  • Model Queries
  • Fastest Check For Existence
  • Application Configuration
  • Application Secrets
  • Useful Things
  • Gems
  • Frameworks
  • Education

Was this helpful?

Ruby on Rails Cheat Sheet

Ruby on Rails Cheat Sheet - A quick reference guide to common ruby on rails commands and usage.

PreviousMigrate attr_encrypted to Rails 7 Active Record encryptsNextPagerTree Forms Integration

Last updated 9 months ago

Was this helpful?

We’ve been doing some Ruby on Rails development lately, in preparation for , and we wanted to put together a Ruby on Rails Cheat sheet. This is a quick reference guide to common ruby on rails commands and usage.

Table of Contents:

Ruby Syntax

Hashes

# Old Syntax
{ :one => "eins", :two => "zwei", :three => "drei" }

# New Syntax
{ one: "eins", two: "zwei", three: "drei" } 
# notice the colon in front of our key
hash = {:one => "eins"} 

hash[:one] # results in "eins"
hash["one"] # results in nil

Safe Navigation Operator

# do this
if user&.email&.verified?

# instead of this
if user && user.email && user.email.verified?

ERB

Evaluation and Output

Evaluation can be done with the <% %> syntax and output can be achieved with the <%= %> syntax.

<% if user.is_subscribed? %>
  You are subscribed to the <%= user.plan.name %> plan!
<% end %>

Partials

You can render partials like so:

<%= render partial: "shared/_nav_links" %>

Rails commands

Common rails commands. (Note: β€œrails g” stands for β€œrails generate”)

Command
Description

rails g model user name:string age:integer account:references

Generates model and migration files

rails g scaffold user name:string age:integer account:references

Generates controller, model, migration, view, and test files. Also modifies config/routes.rb

rails g scaffold_controller user

Generates controller and view files. Useful if you already have the model

Rake Commands

Common rake commands for database management and finding routes.

Command
Description

rake routes

View all routes in application (pair with grep command for some nifty searching)

rake db:seed

Seed the database using the db/seeds.rb

rake db:migrate

Run any pending migrations

rake db:rollback

Rollback a database migration (add STEP=2 to remove multiple migrations)

rake db:drop db:create db:migrate

Destroy the database, re-created it, and run migrations (useful for development)

Rails Framework

Migration Data Types

  • :boolean

  • :date

  • :datetime

  • :decimal

  • :float

  • :integer

  • :primary_key

  • :references

  • :string

  • :text

  • :time

  • :timestamp

Controller Filters

Before filters are registered via the before_action and can halt the request cycle.

controllers/application.rb
class ApplicationController < ActionController::Base
  before_action :require_login

  private

  def require_login
    unless logged_in?
      flash[:error] = "You must be logged in to access this section"
      redirect_to new_login_url # halts request cycle

    end
  end
end

Models Callbacks

New Record
Updating Record
Destroying Record

save

save

destroy

save!

save!

destroy!

create

update_attribute

create!

update

update!

before_validation

before_validation

after_validation

after_validation

before_save

before_save

around_save

around_save

before_create

before_update

before_destroy

around_create

around_update

around_destroy

after_create

after_update

after_destroy

after_save

after_save

after_commit / after_rollback

after_commit / after_rollback

after_commit / after_rollback

models/user.rb
class User < ApplicationRecord
  # Send a welcome email after they are created
  after_create :send_welcome_email
end

Model Queries

Command Example
Description

Model.find(10)

Find model by id

Model.find_by({ name: "Austin" })

Find models where conditions

Model.where("name = ?", params[:name])

Find models where condition

Model.where.not("name = ?", params[:name])

Find models where condition not true

Model.first

Get the first model in the collection (ordered by primary key)

Model.last

Get the lst model in the collection (ordered by primary key)

Model.order(:created_at)

Order your results or query

Model.select(:id, :name)

Select only specific fields

Model.limit(10).offset(20)

Limit and offset (great for pagination)

Fastest Check For Existence

Model.where().exists?

Application Configuration

Application configuration should be located in config/application.rb with specific environment configurations in config/environments/. Don’t put sensitive data in your configuration files, that’s what the secrets are for. You can access configurations in your application code with the following:

Rails.application.config.property_name

Application Secrets

Application secrets are just that, secret (think API keys). You can edit the secrets file using the following commands rails credentials:edit --environment=env_name. This will create files in the config/credentials/ folder. You’ll get two files:

  1. environment.yml.enc - This is your secrets encrypted - This can be put this into git

  2. environment.key - This contains the key that encrypts the file - DO NOT put this into git.

Additionally, when deploying, the key inside the environment.key file will need to be placed into the RAILS_MASTER_KEY environment variable. You can then access secrets in your rails code like so:

Rails.application.credentials[:key_name]

Useful Things

A short list of gems, frameworks and education materials that I have found useful in my Rails journey.

Gems

Frameworks

Education


were one of the most confusing things to me when first starting ruby (not because they are a new concept, but because I found the syntax very hard to read). In newer versions, syntax is very similar to JSON notification. Just know there are two versions of syntax, an older and newer one.

Also, you can have as keys for hashes, and they do not lookup the same values as strings.

Instead of checking for nil or undefined values, you can use the safe navigation operator. There’s a nice article that goes into more depth of explanation.

Migration data types. Here is the and a I commonly reference.

Filters are methods that are run β€œbefore”, β€œafter” or β€œaround” a controller action. See for details.

Gusto has a really nice article one .

This table references the . Check out the full documentation for other special callbacks like after_touch.

A couple of basic (and most commonly used) queries are below. You can find the full documentation .

Additionally, you are likely to want to check for an existence of a condition many times. There are many ways to do this, namely present?, any?, empty?, and exists? but the exists? method will be the fastest. This explains nicely why exists? is the fastest method for checking if one of a query exists.

- Easy multi-tenancy for rails database models.

- Rails engine for flexible admin dashboard.

- Flexible authentication system.

- Provides β€œLogin As” another user functionality for Devise.

- Generate fake data like names, addresses, and phone numbers. Great for test data.

- Expose a hashid instead of primary id to your users.

- Display friendly client side local time.

- Encryption for database fields (model attributes). Just use Rails 7 native encryption. See and .

- Gold standard pagination gem.

- Rack middleware (before Rails) for blocking & throttling.

- A rails Google Recaptcha plugin - You’ll want this one especially for public facing forms to stop bot crawlers.

- A tiny framework for sprinkles of Javascript for your front end.

- Generate scoped ids (ex: per tenant ids for models, aka friendly id).

- Redis backed background processing for jobs.

- A scheduler for Sidekiq (think running weekly email reports).

- Makes web app feels faster (like single page application).

- A SaaS Framework already supporting login, payment (Stripe, Paypal, and Braintree) and multi-tenant setup.

- A utility first CSS framework. Seems a little verbose at first, but you’ll really learn to love it. Just by reading the code, you’ll know exactly what the screen will look like.

- Ruby on Rails tutorials, guides, and screencasts.

I hope you find some value in this cheat sheet. There’s probably a lot I missed on here, so if you have something to add you can reach out to me on and I will update the article with your suggestion.

πŸ’Ž
Hashes
symbols
here
source
stack overflow question
full action controller filters documentation
best practices for model callbacks
ruby on rails documentation for active record callbacks
here
semaphore article
Acts as Tenant
Administrate
Devise
Devise Masquerade
Faker
Hash Id
Local Time
Lockbox
Active Record Encryption
Migrate attr_encrypted to Rails 7 Active Record encrypts
Pagy
Rack Attack
Recaptcha
StimulusJS
Sequenced
Sidekiq
Sidekiq Cron
Turbolinks
Jumpstart Rails
tailwindcss
Go Rails
twitter
PagerTree 4
Ruby Syntax
Hashes
Safe Navigation Operator
ERB
Rails Commands
Rake Commands
Rails Framework
Migration Data Types
Controller Filters
Model Callbacks
Model Queries
Fastest Check For Existence
Application Configuration
Application Secrets
Useful Things
Gems
Frameworks
Education