views:

133

answers:

1

Hi folks. I've been beating my head against the wall on something that on the surface should be very simple. Lets say I have the following simplified models:

user.rb

has_many :memberships  
has_many :groups, :through => :memberships

membership.rb

belongs_to :group  
belongs_to :user  
STATUS_CODES = {:admin => 1, :member => 2, :invited => 3}  
named_scope :active, :conditions => {:status => [[STATUS_CODES[:admin], STATUS_CODES[:member]]}

group.rb

has_many :memberships  
has_many :users, :through => :memberships

Simple, right? So what I want to do is get a collection of all the groups a user is active in, using the existing named scope on the join model. Something along the lines of User.find(1).groups.active. Obviously this doesn't work.

But as it stands, I need to do something like User.find(1).membrships.active.all(:include => :group) which returns a collection of memberships plus groups. I don't want that.

I know I can add another has_many on the User model with conditions that duplicate the :active named_scope on the Membership model, but that's gross.

has_many :active_groups, :through => :memberships, :source => :group, :conditions => ...

So my question: is there a way of using intermediary named scopes when traversing directly between models? Many thanks.

A: 

I believe you can use

User.find(1).memberships.active.collect(&:group)

and this will return all the groups this user is active in.

j.
Unfortunately this doesn't work.
uberllama
uberllama
Of course... my mistake! You need the `collect` part. It's really not very beautiful...
j.
It also results in an array rather than a proper collection. Still hoping for more ideas on this one.
uberllama
It returns an array of `groups`, isn't it? This is the correct behavior
j.
Ideally, I would like a proper collection that could be further chained, such as user.memberships.active.groups.find_by_id(23) or some such. It seems like a gap in AR.
uberllama