title: Getting the intersection of two active record relations, rails
body: <p>In this rails app, I have a method called by a controller that takes an active record relation of sites and an array of filters, the method returns any sites in the relation that have all of the filters in the array. Here is the method:</p>
  
  <pre><code>def filter_sites(sites, filters)
  
    if filters.count &gt; 0
      filterable = sites.tag_join
      filters.each { |f| sites = sites &amp; filterable.with_tag(f) }
    end 
  
    return sites
  end
  </code></pre>
  
  <p>Here are the scope that are used:</p>
  
  <pre><code>def self.tag_join
    joins(:tags).distinct
  end
  
  def self.with_tag(tag_id)
    where('sites_tags.tag_id = ?',tag_id)
  end
  </code></pre>
  
  <p>This is functioning correctly but the problem is that it returns an array. My question is; is there a more effective way or writing this method and returning an active record relation? As later on in the code, further queries need to be chained.</p>
  
  <p>Any help greatly appreciated.</p>