3

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.

Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
uberllama
  • 18,752
  • 2
  • 16
  • 8

1 Answers1

0

I believe you can use

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

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

Ju Nogueira
  • 8,435
  • 2
  • 29
  • 33
  • Something similar does work, but its pretty ugly: user.memberships.active.all(:include => :group).collect(&:group) – uberllama May 06 '10 at 21:43
  • Of course... my mistake! You need the `collect` part. It's really not very beautiful... – Ju Nogueira May 07 '10 at 00:20
  • It also results in an array rather than a proper collection. Still hoping for more ideas on this one. – uberllama May 07 '10 at 13:48
  • It returns an array of `groups`, isn't it? This is the correct behavior – Ju Nogueira May 07 '10 at 15:26
  • 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 May 08 '10 at 16:19