Ruby on Rails Cheat Sheet
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
- Rails Commands
- Rake Commands
- Rails Framework
- Useful Things
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.
Also, you can have symbols as keys for hashes, and they do not lookup the same values as strings.
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.
Evaluation and Output
Evaluation can be done with the
<% %> syntax and output can be achieved with the
<%= %> syntax.
You can render partials like so:
Common rails commands. (Note: “rails g” stands for “rails generate”)
||Generates model and migration files|
||Generates controller, model, migration, view, and test files. Also modifies
||Generates controller and view files. Useful if you already have the model|
Common rake commands for database management and finding routes.
||View all routes in application (pair with
||Seed the database using the
||Run any pending migrations|
||Rollback a database migration (add STEP=2 to remove multiple migrations)|
||Destroy the database, re-created it, and run migrations (useful for development)|
Migration Data Types
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.
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
|New Record||Updating Record||Destroying Record|
|after_commit / after_rollback||after_commit / after_rollback||after_commit / after_rollback|
A couple of basic (and most commonly used) queries are below. You can find the full documentation here.
||Find model by id|
||Find models where conditions|
||Find models where condition|
||Find models where condition not true|
||Get the first model in the collection (ordered by primary key)|
||Get the lst model in the collection (ordered by primary key)|
||Order your results or query|
||Select only specific fields|
||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.
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:
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:
environment.yml.enc- This is your secrets encrypted - This can be put this into git
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:
A short list of gems, frameworks and education materials that I have found useful in my Rails journey.
- 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).
- 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.
- 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).
- 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.
- Go Rails - Ruby on Rails tutorials, guids, 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.