Rails Commands Cheatsheet
General Guides
Destroy Associated Records When Parent Records Are Deleted
class Users < ActiveRecord::Base
has_many :items, dependent: :destroy_all
end
Warning, there is a difference between #delete
and #destroy
Generators
Generate The Scaffold For A Model
The command format is rails g scaffold <name of model> <model attributes>
bin/rails g scaffold ModelName name:string email:string description:text price:decimal
Generate A Rails Model
bin/rails g model ModelName name:string email:string description:text price:decimal seller_id:integer img_url:string
You can undo the generation with
bin/rails destroy model ModelName name:string email:string description:text price:decimal seller_id:integer img_url:string
Model Validations
Validate email format
class User < ApplicationRecord
validates :email, presence: true,
uniqueness: true,
# Uses a constant built into URI in the standard ruby library
format: {with: URI::MailTo::EMAIL_REGEXP}
end
Misc
A Nicer Print Out Of Rails Routes
rails routes --expanded
Can pipe into grep to search for specific string patterns
rails routes --expended | grep SEARCH_PATTERN
See all available rake tasks
rake --tasks
Implementation Guides
Additional resources
- Lifecycle Of A Request In Rails
- What Is Rack
- Introducing Rack
- Big idea: Rack is just 2 things
- A convention / agreed-upon protocol of how ruby “applications” should be structured so that web servers know what to expect
- Framework developers can implement the agreed-upon Rack specs/interface that web servers would build their interface for
- A gem with a library of helper methods, modules and middleware for framework developers to use if they want
- Instead of each framework developer building the Rack specs/interface from scratch every time, they can use Rack as a gem with all the middleware and utilities to act as the middle layer between the webservers and the framework
- A convention / agreed-upon protocol of how ruby “applications” should be structured so that web servers know what to expect