views:

69

answers:

1
class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships

  def moderators
    # relationship_id is in the memberships table
    self.users.find(:all, :conditions => ['relationship_id = ?', 1])
  end
end

Given the above code, is this the best way to implement the moderators method? My goal is to be able to find all the users with a "moderator" relationship within a given group. Right now I can use the method to iterate over all the moderators

# ...
@group.moderators

I considered an association extension which makes sense to use here because I'm asking for a subset of users that meet a condition. But the syntax seems redundant to ask for users that are moderators

# Association extension - seems redundant
@group.users.moderators

I considered a named_scope but I couldn't figure out how to implement it without errors. Even if I could the named_scope will return all the moderators across all the groups which isn't what I want.

# named_scope: returns all the moderators across all the groups
moderators = Group.moderators

I'm wondering what the best practice here is and why I might want to us an association extension (or named_scope) over the instance method given that it allows for a more concise syntax?

A: 

Add an association on Group class:

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships

  has_many :moderators, :source => :user, :through => :memberships, 
                :conditions => ['relationship_id = ?', 1]
end

Now you can do the following:

 @group.moderators
 @group.moderators.size
 @group.moderators.find_by_city(..)
KandadaBoggu
Perfect! I read right over that in AWDWR and didn't realize it. Thanks for spotlighting that. Is doing this functionally the exact same as using instance methods or are there other benefits to adding a conditional association?
Brandon Toone
They are not the same as instance methods. You can chain the methods of an association and named_scope defined on on User class.
KandadaBoggu