Show Menu
Cheatography

Rails 4 Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Active Record: Query

User.all
User.f­ind­(pa­ram­s[:id])
User.f­ind­_by­(name: params­[:n­ame])
User.w­her­e(e­mail: params­[:e­mail])
User.w­her­e("s­ign­_in­_count > 1")
User.w­her­e("age > 18").li­mit(5)
User.w­her­e(g­ender: "­M").o­rd­er(­:name)
User.f­ind­_ea­ch(­bat­ch_­size: 5000)
@users.pl­uck­(:e­mail)

Active Record: Agregation

Person.av­era­ge(­:age)
Trade.m­ax­imu­m(:­price)
Order.g­ro­up(­:st­atu­s).c­ount
Person.co­unt­(:all)

Command Line

rails (s)erver
rails (c)onsole
rails (g)enerate
rake db:migrate
rake db:mig­rat­e:s­tatus
rake routes

Routes

root :to => 'pages­#ho­me_­page'
get '/pati­ent­s/:id', to: 'patie­nts­#show'
resources :photos
namespace :admin do ... end

Forms

form_f­or(­@model) do |f| ... end
link_to 'name', path
f.label
f.text­_field
f.pass­wor­d_field
f.emai­l_field
f.submit
 

Active Record: Create / Update

User.c­rea­te(­name: "­Dav­id", occupa­tion: "Code Artist­")
@user.u­pd­ate­(name: "­Dav­e")
@user.d­estroy
@user.save / @user.s­ave!
User.f­ind­_or­_cr­eate_by
User.w­her­e(some condit­ion­).f­irs­t_o­r_c­rea­te(­params)

Valida­tions

validates :name, :presence => true
validates :name, :length => { :minimum => 2 }
validates :password, length: { in: 6..20 }
validates :email, :uniqu­eness => true
validates :count, :numer­icality => { :great­er_than => 0 }
validates :size, inclusion: { in: %w(small medium large) }

Migrations

create­_table :table do |t| ... end
add_column :table, :field, :type
change­_column :table, :field, :type
rename­_column :table, :name, :new_name
rename­_table
add_index

Misc

before­_action :method
scope :publi­shed, -> { where(­pub­lished: true) }

Active Record: Data Types

string
float
integer
text
time
date
boolean

Active Record: Associ­ations

:has_one
:has_many / :belon­gs_to