views:

713

answers:

3

Is there a way to combine scopes in an additive fashion?

If I have the scopes

User.big_haired

and

User.plays_guitar

I can call

User.big_haired.plays_guitar

and get all the users who have big hair AND play guitar. Can I write this to get all users who have big hair OR play guitar?

I guess I have to add that I realize that you can run a set of queries and add the results together. That's what I'm trying not to do.

+2  A: 

So you have:

class User < ActiveRecord::Base
  named_scope :big_haired, :conditions => {:hair => 'massive'}
  named_scope :plays_guitar, :conditions => {:plays => 'guitar'}
end

User.big_haired.plays_guitar => Lots of users.

I am unaware of a method to mash the two together. Perhaps just blending the arrays:

@users = (User.big_haired + User.plays_guitar).uniq
askegg
A: 

I just tried this out on some of my models that have named_scopes defined. It will put the conditions together as an AND condition if you combine it. So...

User.big_haired.plays_guitar

will result in (obviously my shorthand SQL, not the real rails generated stuff)

SELECT * FROM users WHERE hair = 'massive' AND plays = 'guitar'

I don't know of a way to combine them as an OR relationship. That would be incredibly complex to mix in when you think about the various options. We chain named_scopes all the time, it works well (as long as you want them ANDed together).

To do the and case, I would either create a special named scope with the OR conditions built on, or use a union to produce a unique set like so:

User.big_haired | User.plays_guitar
Jeff Whitmire
+2  A: 

Try Searchlogic, it recently supports combining named scopes with OR

Shane Mingins