views:

1592

answers:

3

as an example, i have a model Group and model User

they are connected with :has_many, :through => groups_users

groups_users table has an attribute, called moderator, specifying whether a user is a moderator of the group

question: how do i access all moderators of a given group?

after reading about :with_scope, what comes to mind is

def find_moderators
 Group.with_scope(:find=>{:conditions => "moderator=1"})
   @[email protected]
 end
end

However, after rails 2, with_scope becomes protected, and doesn't allow given code in the controller, so What is the good alternative to that?

A: 

Monkeypatch!

class Group < ActiveRecord::Base
   public :with_scope
end
mcandre
using named_scope is way better than doing this.
Matt Van Horn
A: 
class User
  has_many :group_users
  has_many :groups, :through => :groups_users
end

class GroupUser
  belongs_to :user
  belongs_to :group
  named_scope :as_moderator, :conditions => "moderator=1"
end

class Group
  has_many :group_users
  has_many :groups, :through => :groups_users
  def moderators
    group_users.as_moderator.map{|gu|gu.user}
  end
end

# use it:
@moderators = @group.moderators
or
@all_mods = Group.all.map{|g|g.moderators}.flatten
Matt Van Horn
+1  A: 

solved with

class Group
  has_many :group_users
  has_many :groups, :through => :groups_users
  has_many :moderators, :through => :group_users, :class_name => "User", :source => :user, :conditions => ['groups_users.moderator = ?',true]
end

Preferred to Matt van Horn's answer because this one produces only one query when we select user info with @group.moderators, while his solution gives separate query for each moderator

Pavel K.
I think using the :include => :user option on the named_scope would solve the multiple queries issue.named_scope :as_moderator, {:include => :user, conditions => "moderator=1"}But the has_many solution seems to fit your semantics better and is more elegant, I think.
Matt Van Horn