2013-03-08 55 views
0

我有一个这样的小组班。团队有很多人。我有办法将多个Active Record关系合并为一个查询吗?

class Group < ActiveRecord::Base 
    has_many :people 
    def notices 
    Notice.where(:person_id => people).where("radius <= ?", radius) 
    end 
end 

在我的通知控制器中,我想显示来自所有用户组的所有通知,没有重复。 目前我正在这样做,这是跛脚。有没有办法将来自每个组的查询合并为一个关系而不是一个数组?

class NoticesController < ApplicationController 
    def index 
    @groups = current_person.groups 
    @notices = [] 
    @groups.each do |g| 
     @notices += g.notices 
    end 
    end 
end 

感谢

+0

你可以给一个更具体的例子?你是否有条件地链接活动记录查询? – jvnill 2013-03-08 13:08:24

+0

让我编辑一个更具体的问题 – superluminary 2013-03-08 13:12:14

+1

成员是什么? – 2013-03-08 13:22:09

回答

2

我假设有一个人模型。

好的。

试试这个。

在Person模型,添加这个

has_many :all_group_members, through: :groups, class_name: "Person" 

再加入此方法

def all_notices 
    Notice.where(:person_id => all_group_members.pluck(:id)).where("radius <= ?", radius) 
end 

最后在你的控制器u能做到这一点

current_person.all_notices