Using named_scopes on the join model of a has_many :through

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.

Answers


I believe you can use

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

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


Need Your Help

Send php mail to user if form submitted

php phpmailer

I am trying to use the phpmail function to send an email to a user if their post was accepted. First I am capturing the user email in a query if a form is submitted, but I'm not sure how to impleme...

package in java equals to what in C#?

c# java

There is a package in JAVA named for example: