Comment on page
💎
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:
- 1.
- 1.
- 3.
- 2.
- 3.
- 5.
- 1.
- 2.
- 3.
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" }
# notice the colon in front of our key
hash = {:one => "eins"}
hash[:one] # results in "eins"
hash["one"] # results in nil
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?
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 %>
You can render partials like so:
<%= render partial: "shared/_nav_links" %>
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 |
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) |
- :boolean
- :date
- :datetime
- :decimal
- :float
- :integer
- :primary_key
- :references
- :string
- :text
- :time
- :timestamp
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
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 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
A couple of basic (and most commonly used) queries are below. You can find the full documentation here.
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) |
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 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 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]
A short list of gems, frameworks and education materials that I have found useful in my Rails journey.
- 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.
- Recaptcha - A rails Google Recaptcha plugin - You’ll want this one especially for public facing forms to stop bot crawlers.
- 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.
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.