1

例如,我有一个模型组和模型用户

它们与 :has_many, :through => groups_users 连接

groups_users 表有一个属性,称为 moderator,指定用户是否是组的主持人

问题:我如何访问给定组的所有版主?

在阅读了 :with_scope 之后,我想到的是

def find_moderators
 Group.with_scope(:find=>{:conditions => "moderator=1"})
   @moderators=@group.users
 end
end

但是,在 rails 2 之后,with_scope 受到保护,并且不允许控制器中的给定代码,那么有什么好的替代方法呢?

4

3 回答 3

3

解决了

class Group
  has_many :groups_users
  has_many :moderatorships, :class_name => "GroupsUser",:conditions => {:moderator => true}
  has_many :moderators, :through => :moderatorships, :class_name => "User", :source => :user
end

首选 Matt van Horn 的答案,因为当我们使用 @group.moderators 选择用户信息时,这个答案只产生一个查询,而他的解决方案为每个主持人提供单独的查询

编辑:更新以回答 Sizzlepants 的问题。使用此代码创建的主持人应将连接模型中的主持人属性设置为 true(rails 在创建连接模型时使用 :conditions),此外,如果我现在必须对其进行编码,我会命名 groups_users 成员资格以提高可读性。

于 2009-08-18T07:52:01.320 回答
0
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
于 2009-08-17T14:28:29.160 回答
-2

猴子补丁!

class Group < ActiveRecord::Base
   public :with_scope
end
于 2009-08-17T14:24:51.070 回答