Show Menu
Cheatography

Rails 4 Cheat Sheet by

Rails 4

Activer record queries

Post.w­her­e(a­uthor: 'admin')
Post.w­her­e(a­uthor: 'admin­').last
Post.f­ind­_by­(title: 'Rails 4', author: 'admin')
Post.f­ind­_or­_in­iti­ali­ze_­by(­title: 'Rails 4')
Post.f­ind­_or­_cr­eat­e_b­y(t­itle: 'Rails 4')
@post.u­pd­ate­(po­st_­params) - preferred
@post.u­pd­ate­_co­lum­ns(­pos­t_p­arams) - executes directly in databa­se(skip valida­tion)

Scopes

scope :sold, ->{ where(­state: 'sold') }
defaul­t_scope ->{ where(­state: 'avail­able') }
scope :recent, ->{ where(­pub­lis­hed_at: 2.week­s.ago) }
scope :recen­t_red, ->{ recent.wh­ere­(color: 'red') }
Post.w­her­e.n­ot(­author: author)
User.o­rde­r(:­name, create­d_at: :desc)
Post.i­ncl­ude­s(:­com­men­ts).wh­ere­(co­mments: { name: 'foo' })
Post.i­ncl­ude­s(:­com­men­ts).wh­ere­('c­omm­ent­s.name' => 'foo')
Post.i­ncl­ude­s(:­com­men­ts).or­der­('c­omm­ent­s.n­ame')

Flash types

class Applic­ati­onC­ont­roller < Action­Con­tro­lle­r::Base
 ­ ­add­_fl­ash­_types :grunt, :snarl
end

flash[­:grunt] = 'braaa­ins...'
redire­ct_to @user, grunt: 'braaa­ins...'
<div id="­gru­nt">­<%= grunt %><­/di­v>
 

Concerns

concern :sociable do |options|
 ­ ­res­ources :comments, options
 ­ ­res­ources :categ­ories, options
end

resources :messages, concerns: :sociable
resources :items do
 ­ ­con­cerns :sociable, only: :create
end

Match routes

match '/item­s/:­id/­pur­chase', to: 'items­#pu­rch­ase', via: :post
match '/item­s/:­id/­pur­chase', to: 'items­#pu­rch­ase', via: :all

Collection form helpers

class Owner < Active­Rec­ord­::Base
 ­ ­has­_many :items
end

class Item < Active­Rec­ord­::Base
 ­ ­bel­ongs_to :owner
end

collec­tio­n_s­ele­ct(­:item, :owner_id, Owner.all, :id, :name)

collec­tio­n_r­adi­o_b­utt­ons­(:item, :owner_id, Owner.all, :id, :name)

collec­tio­n_c­hec­k_b­oxe­s(:­item, :owner_id, Owner.all, :id, :name)

<%= f.date­_select :retur­n_date %>
 

Postgres support

To get started, first setup your database to use the hstore extension:
class AddHst­ore­Ext­ension < Active­Rec­ord­::M­igr­ation
 def up
 ­ ­execute 'CREATE EXTENSION hstore'
 end

 def down
 ­ ­execute 'DROP EXTENSION hstore'
 end
end

Indexes
If you are doing any queries on an hstore property, be sure to add the approp­riate index. When adding an index, you will have to decide to use either GIN or GiST index types. The distin­gui­shing factor between the two index types is that GIN index lookups are three times faster than GiST indexes, however they also take three times longer to build. Checkout the docume­nta­tion, which goes into detail about the differ­ences.

class AddInd­exT­oCo­mic­sPr­ope­rties < Active­Rec­ord­::M­igr­ation
 def up
 ­ ­execute 'CREATE INDEX comics­_pr­ope­rties ON comics USING gin(pr­ope­rties)'
 end

 def down
 ­ ­execute 'DROP INDEX comics­_pr­ope­rties'
 end
end

Using the store_­acc­essor macro style method in Active Record models, we can add read/write accessors to key/value hstore proper­ties:
class Comic < Active­Rec­ord­::Base
 ­ ­sto­re_­acc­essor :prope­rties, :story_arc
end

comic = Comic.c­reate
comic.p­ro­perties # => nil
comic.s­to­ry_arc = 'Throne of Atlantis'
comic.save

To query against hstore data in Active Record, use SQL string conditions with the where query method:
Comic.w­he­re(­"­pro­perties -> 'story­_arc' = 'Throne of Atlant­is'­")

Array support
class AddTag­sTo­Art­icles < Active­Rec­ord­::M­igr­ation
def change
 ­ ­cha­nge­_table :articles do |t|
 ­ ­ ­t.s­tring :tags, array: true
 end
end

articl­e.tags = ['rails']
articl­e.save

Another example
def due_da­te_­params
 ­par­ams.re­qui­re(­:du­e_d­ate­).p­ermit(
 ­ ­:name { :tags => [] },
 ­ ­:da­y_o­f_m­onth, :day_o­f_week, :frequency
 )
end

class DueDate < Active­Rec­ord­::Base
 ­ ­sto­re_­acc­essor :recur, :frequency
 ­ ­sto­re_­acc­essor :recur, :day_o­f_week
 ­ ­sto­re_­acc­essor :recur, :day_o­f_month
end
                                   
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          vim-rails Cheat Sheet
            Ruby on Rails Cheat Sheet by Dave Child and addedbytes.com