3

Hi I have a named_scope in my User model as following.

named_scope :by_gender, lamdba { |gender| { :conditions => { :gender => gender } } }

I want to create other two named scopes which re use this one something like,

named_scope :male,   lambda { by_gender('male') }
named_scope :female, lambda { by_gender('female') }

Any idea what to do?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Waseem
  • 8,232
  • 9
  • 43
  • 54

1 Answers1

3

You could provide class methods that perform the hardwired argument passing:

def self.male
    by_gender('male')
end

def self.female
    by_gender('female')
end

or, as the named_scope you are using is so simple you could cut out the by_gender scope and simply use:

named_scope :male, :conditions => {:gender => 'male'}
named_scope :female, :conditions => {:gender => 'female'}

The second option is of course conditional on you not actually requiring the by_gender scope explicitly anywhere else.

workmad3
  • 25,101
  • 4
  • 35
  • 56
  • Hmmm providing class methods makes sense. It will return an association proxy so I can even chain them together. Thanks. – Waseem Oct 26 '09 at 16:20