BeeZee
BeeZee

Reputation: 1602

Instance method, named_scope or association extension

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?

Upvotes: 0

Views: 597

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

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(..)

Upvotes: 1

Related Questions