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 に答える