superluminary
superluminary

Reputation: 49162

I there a way to combine more than one Active Record relation into a single query?

I have a group class like this. Groups have many people.

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

In my notices controller, I want to show all notices from all the users groups, without duplication. Currently I'm doing this, which is lame. Is there a way to combine the queries from each group to return a relation, rather than an Array?

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

Thanks

Upvotes: 0

Views: 38

Answers (1)

Abibullah Rahamathulah
Abibullah Rahamathulah

Reputation: 2891

I am Assuming There is A Person Model.

Okay.

Try This.

In Person model, Add this

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

then add this method

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

Finally in your controller u can do this

current_person.all_notices

Upvotes: 2

Related Questions