Take the 2-minute tour ×

I have two scopes

named_scope :by_foo, lambda { |foo| { :conditions =>  {:foo => foo} } }
named_scope :by_bar, lambda { |bar| { :conditions =>  ["bar like ?", bar+"%"] } }

How I can mix them together in one scope without chaining ?

named_scope :by_baz # what that should look like ?   
share|improve this question

2 Answers 2

up vote 4 down vote accepted

named_scope :by_baz, lambda {|args| by_foo(args[:foo]).by_bar(args[:bar])}

You could call it by:

Model.by_baz({:foo=>value, :bar=>value})

This way you could add as much scopes as you like without rewriting the condition.

share|improve this answer
Very readable and DRY solution, awesome, thx –  astropanic Mar 21 '12 at 8:50
named_scope :by_foo_and_bar, lambda { |foo, bar| { :conditions =>  ["foo = ? AND bar like ?", foo, bar+"%"] } }
share|improve this answer
Thanks, but this implicts code duplication, when You change one of the input scopes, you need to rewrite this too –  astropanic Mar 21 '12 at 8:51

Your Answer


