Let’s say i want to be able to retrieve doggie’s red shirts:
12345678910
classDog# (blah blah)defred_shirtsshirts.where(:color=>'red')endenddoggie.shirts# all shirtsdoggie.red_shirts# all red shirts
Ok, what if we want to retrieve kitty’s red shirts as well ?
12345678910
classCat# (blah blah)defred_shirtsshirts.where(:color=>'red')endendkitty.shirts# all shirtskitty.red_shirts# all red shirts
Hmmm, duplication detected, but not so bad (yet) .. how abt i
want to retrieve all red shirts ? AR supports this via the
scope declarative:
123456789101112
classShirt# (blah blah)scope:red,where(:color=>'red')# * A less DSL-ish approach is to declare a class method# def self.red# where(:color => 'red')# endendShirt.red# all red shirts
And you know what, with the new Shirt.red, i can throw away
Cat#red_shirts & Dog#red_shirts. If i ever want to fetch
the red shirts of doggie & kitty:
12345
doggie.shirts# all doggie's shirtsdoggie.shirts.red# all doggie's red shirtskitty.shirts# all kitty's shirtskitty.shirts.red# all kitty's red shirts
And to make it even sweeter, i can do the following as well:
12
doggie.shirts.red.create(:size=>:xl)# doggie gets a new red :xl shirtkitty.shorts.red.create(:size=>:xs)# kitty gets a new red :xs shirt