2010-04-16 59 views
0
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 

鉴于上述代码,这是实现moderators方法的最佳方法吗?我的目标是能够在给定组中找到具有“主持人”关系的所有用户。现在,我可以使用的方法来遍历实例方法,named_scope或关联扩展

# ... 
@group.moderators 

我认为一个协会扩展,它是有道理的用在这里,因为我要求对符合条件的用户的一个子集的所有主持人。但语法似乎多余的要求是主持人的用户

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

我认为是一个named_scope,但我无法弄清楚如何实现它没有错误。即使我能够将named_scope返回到所有组中的所有主持人,这些都不是我想要的。

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

我想知道什么在这里最好的做法是,为什么我会想我们的关联扩展(或named_scope)在实例方法因为它允许一个更简洁的语法?

回答

1

在组类添加关联:

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

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

现在,你可以做到以下几点:

@group.moderators 
@group.moderators.size 
@group.moderators.find_by_city(..) 
+0

完美!我在AWDWR上阅读过它,并没有意识到这一点。感谢聚光灯。在功能上做这个和使用实例方法完全一样,还是增加一个条件关联还有其他好处吗? – caspyin 2010-04-16 17:30:00

+0

它们与实例方法不同。您可以链接在User类上定义的关联方法和named_scope。 – 2010-04-16 18:21:36