title: Rails multiple joins condition query for exact tags with has many through relationships
body: <p>I have a problem with filtering products by exact tags as my current query does not return exact matches and I can't seem to get the right query conditions. </p>
  
  <p><strong>Example</strong></p>
  
  <p><code>Area = ["small","big"]</code> ,<code>Surface = ["smooth","rough"]</code></p>
  
  <p>Product A has only <code>["small","smooth","rough"]</code> as tags </p>
  
  <p>If I filter products using <code>["small","big","smooth","rough"]</code> as the tags, I get product A in my search results but ideally, it should not return any search results.</p>
  
  <p>I have three models, <code>Product</code>,<code>Area</code> and <code>Surface</code>.  <code>Area</code> &amp; <code>Surface</code> are linked to <code>Product</code> by a <code>has_many through</code> relationship.</p>
  
  <pre><code>class Product &lt; ActiveRecord::Base
    has_many :product_areas
    has_many :areas, :through =&gt; :product_areas
    has_many :product_surfaces
    has_many :surfaces, :through =&gt; :product_surfaces
  
  class Area &lt; ActiveRecord::Base
    #Surface model looks exactly the same as Area model
    has_many :product_areas,dependent: :destroy
    has_many :products, :through =&gt; :product_areas
  </code></pre>
  
  <p><strong>My Query</strong></p>
  
  <pre><code>area_ids = params[:area_ids]
  surface_ids = params[:surface_ids]
  @products = Product.where(nil)
  @products = @products.joins(:areas).where('areas.id' =&gt; area_ids).group('products.id').having("count(areas.id) &gt;= ?",area_ids.count) unless area_ids.blank?
  @products = @products.joins(:surfaces).where('surfaces.id' =&gt; surface_ids).group('products.id').having("count(surfaces.id) &gt;= ?",surface_ids.count) unless surface_ids.blank?
  </code></pre>