Additive Chaining with named_scope Additive Chaining with named_scope ruby-on-rails ruby-on-rails

Additive Chaining with named_scope


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


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