title: Apply scope to association on Rails
body: <p>I've a <code>products</code> table and <code>product_variants</code>, which has a <code>has_many</code> relationship with <code>products</code></p>
  
  <p>I want to retrieve all available products and its available variants.</p>
  
  <p>The <code>Product</code> model:</p>
  
  <pre><code>class Product &lt; ApplicationRecord
    scope :only_enabled,   -&gt; { where(status: :enabled) }
    scope :only_in_stock,  -&gt; { where('quantity &gt; 0') }
    scope :only_available, -&gt; { only_enabled.only_in_stock }
  end
  </code></pre>
  
  <p>and the <code>ProductVariant</code> model:</p>
  
  <pre><code>class ProductVariant &lt; ApplicationRecord
    scope :only_enabled,   -&gt; { where(status: :enabled) }
    scope :only_in_stock,  -&gt; { where('inventory_quantity &gt; 0') }
    scope :only_available, -&gt; { only_enabled.only_in_stock }
  end
  </code></pre>
  
  <p>How can I retrieve all <code>Product.only_available</code> with its <code>ProductVariant.only_available</code>, not excluding the products if the variants don't match the <code>ProductVariant.only_available</code> scope?</p>
  
  <p>I've tried to use this query:</p>
  
  <pre><code>@store.products.only_available.joins(:category).joins('LEFT JOIN product_variants ON product_variants.product_id = products.id AND product_variants.status = 1 AND product_variants.inventory_quantity &gt; 0')
  Product Load (4.4ms)  SELECT "products".* FROM "products" INNER JOIN "categories" ON "categories"."id" = "products"."category_id" LEFT JOIN product_variants ON product_variants.product_id = products.id AND product_variants.status = 1 WHERE "products"."store_id" = $1 AND "products"."status" = $2 AND (quantity &gt; 0) ORDER BY "products"."name" ASC  [["store_id", "129031"], ["status", 1]]
  </code></pre>
  
  <p>The problem is that it doesn't seem to be filtering the unavailable variants.</p>