0

我有一个这样的小组课。团体有很多人。

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

谢谢

4

1 回答 1

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

最后在你的控制器中你可以做到这一点

current_person.all_notices
于 2013-03-08T13:27:59.517 回答