实例方法,named_scope或关联扩展

时间:2010-04-16 16:06:37

标签: ruby-on-rails

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方法的最佳方法吗?我的目标是能够在给定的组中找到具有“主持人”关系的所有用户。现在我可以使用该方法迭代所有主持人

# ...
@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 个答案:

答案 0 :(得分:1)

在Group类上添加关联:

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