0

给定以下模型:

User (id)
  has_many :groups
  has_many :communities

Groups (community_id (OPTIONAL) )
  belongs_to :user
  belongs_to :community

Communities (id, archived (boolean) )
  has_many :groups
  has_many :group_members, :include => :user

我可以通过以下方式轻松获取用户组:

current_user.groups

问题是如果一个社区被归档,我不希望它在 current_user.groups 中返回。

如何获取社区未存档的所有用户组?

谢谢

4

2 回答 2

1

current_user.groups.joins(:community).where('communities.archived' => false)

于 2012-07-13T21:25:40.810 回答
0

这可能有点笨拙,但您可以轻松地循环 current_user.groups,并检查每个组的社区是否已存档。也许是这样的

all_groups = current_user.groups
final_list = []
all_groups.each { |g| 
  if !g.community.archived
    final_list << g
  end
}

这将遍历所有的current_user组并检查每个组是否已存档。如果没有,它会将其添加到一个名为final_list. 可能有更优雅的方式来做这件事,但这至少让你知道你应该做什么。

于 2012-07-13T21:21:07.943 回答