Rails Backend Cheatsheet
Rails Backend Cheatsheet
Environment structure:
- app/: core logic (MVC)
- config/: environment, routes, DB, initializers
- db/: seeds, schema, migrations
- test/ or spec/: unit/integration tests
Options:
null: false
default: 0
index: true
foreign_key: true
Associations:
belongs_to, has_many, has_one, has_and_belongs_to_many
Self-reference:
class Employee < ApplicationRecord
belongs_to :manager, class_name: 'Employee', optional: true
has_many :subordinates, class_name: 'Employee', foreign_key: :manager_id
To_table usage:
add_reference :orders, :buyer, foreign_key: { to_table: :users }
schema.rb:
Auto-generated canonical representation of DB (not SQL dump)
Used to recreate structure on new environments
First-time:
rails g migration CreateProducts name:string price:decimal
Change column:
rails g migration AddViewsToArticles views:integer
rails g migration RemoveViewsFromArticles views:integer
rails g migration RenameViewsToHitsInArticles
rails g migration ChangeDataTypeForViews
Manual editing:
change_table, add_column, remove_column
add_index, add_foreign_key
Timestamps:
t.timestamps # Adds created_at, updated_at
5. Validations
def valid_future_publish_date
if publish_at && publish_at < Time.current
errors.add(:publish_at, "must be in the future")
end
end
end
$ rails console
Ruby on Rails Comprehensive Backend Cheat Sheet
Model.find(id)
Model.find_by(email: "x")
Model.where(active: true)
Model.order(created_at: :desc)
Model.limit(10).offset(20)
Model.group(:status).count
Model.joins(:comments)
Model.includes(:user)
Model.select("id, name").where("age > ?", 18)
Model.exists?(conditions)
8. Controller generation
$ rails g controller Articles index show new edit create update destroy
Options:
--skip-routes Don't add routes automatically
--skip-template-engine Avoid view templates
9. Routing
Manual:
get '/posts', to: 'posts#index'
resources :posts
resources :users do
resources :posts
end
def index
Ruby on Rails Comprehensive Backend Cheat Sheet
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render :new, status: :unprocessable_entity
end
end
params[:id]
params[:user][:name]
Strong parameters:
def user_params
params.require(:user).permit(:name, :email)
end
13. Partials
_filename.html.erb is a partial
$ rails server
$ rails s -p 3001 -b 0.0.0.0