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

rails, cheatsheet