title: There is an entry for table "stores", but it cannot be referenced from this part of the query
body: <p>I want to select latest 4 deals from my stores, with has_and_belongs_to_many relationship, and Im getting this error:</p>
  
  <blockquote>
    <p>There is an entry for table "stores", but it cannot be referenced from
    this part of the query</p>
  </blockquote>
  
  <pre><code>class Deal &lt; ActiveRecord::Base
     has_and_belongs_to_many :stores
  end
  
  class Store &lt; ActiveRecord::Base
     has_and_belongs_to_many :deals
  end
  </code></pre>
  
  <p>My Query</p>
  
  <pre><code>SELECT * FROM (SELECT stores.id AS store_id,       deals.*,
        dense_rank() OVER (
          PARTITION BY deals.stores.id
          ORDER BY deals.created_at DESC
        ) AS deal_rank
   FROM "deals" 
   INNER JOIN "listings" 
   ON "listings"."deal_id" = "deals"."id" 
   INNER JOIN "images" 
   ON "images"."id" = "deals"."image_id" 
   INNER JOIN "deals_stores" 
   ON "deals_stores"."deal_id" = "deals"."id" 
   INNER JOIN "stores" 
   ON "stores"."id" = "deals_stores"."store_id"  
   ORDER BY deals.created_at desc) 
   AS ranked_deals  
   WHERE (deal_rank &lt;= 4)
  </code></pre>