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开发者_如何学JAVA 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.
I believe you can use
User.find(1).memberships.active.collect(&:group)
and this will return all the groups this user is active in.
精彩评论