Additive Chaining with named_scope
Asked Answered
M

3

9

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.

Maulmain answered 12/8, 2009 at 2:36 Comment(0)
A
2

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
Advisement answered 12/8, 2009 at 3:10 Comment(0)
C
2

Try Searchlogic, it recently supports combining named scopes with OR

Chicoine answered 31/8, 2009 at 22:39 Comment(0)
A
0

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
Anaerobic answered 12/8, 2009 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.