💎Ruby on Rails Cheat Sheet

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

We’ve been doing some Ruby on Rails development lately, in preparation for PagerTree 4, 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

Hashes 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.

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

# New Syntax
{ one: "eins", two: "zwei", three: "drei" } 

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

# notice the colon in front of our key
hash = {:one => "eins"} 

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

Safe Navigation Operator

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

# 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”)

CommandDescription

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.

CommandDescription

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

Migration data types. Here is the source and a stack overflow question I commonly reference.

  • :boolean

  • :date

  • :datetime

  • :decimal

  • :float

  • :integer

  • :primary_key

  • :references

  • :string

  • :text

  • :time

  • :timestamp

Controller Filters

Filters are methods that are run “before”, “after” or “around” a controller action. See full action controller filters documentation for details.

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

Gusto has a really nice article one best practices for model callbacks.

This table references the ruby on rails documentation for active record callbacks. Check out the full documentation for other special callbacks like after_touch.

New RecordUpdating RecordDestroying 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

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

Command ExampleDescription

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

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 semaphore article explains nicely why exists? is the fastest method for checking if one of a query exists.

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

  • Acts as Tenant - Easy multi-tenancy for rails database models.

  • Administrate - Rails engine for flexible admin dashboard.

  • Devise - Flexible authentication system.

  • Devise Masquerade - Provides “Login As” another user functionality for Devise.

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

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

  • Local Time - Display friendly client side local time.

  • Lockbox - Encryption for database fields (model attributes). Just use Rails 7 native encryption. See Active Record Encryption and Migrate attr_encrypted to Rails 7 Active Record encrypts.

  • Pagy - Gold standard pagination gem.

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

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

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

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

  • Sidekiq - Redis backed background processing for jobs.

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

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

Frameworks

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

  • tailwindcss - 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.

Education

  • Go Rails - 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 twitter and I will update the article with your suggestion.

Last updated