title: Rails: query the existence of a join table's child
body: <p>Setup:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :sales
    has_many :sold_items, through: :sales, source: item
    has_many :returns, through: sold_items
  end
  
  class Sale &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :item
    has_one :return
  end
  
  class Item &lt; ActiveRecord::Base
    has_many :sales
    has_many :returned_sales, through: :sales, source: :return
  end
  
  class Return &lt; ActiveRecord::Base
    belongs_to :sale
  end
  </code></pre>
  
  <p><strong>Question:</strong></p>
  
  <p>Edit: Clarify question. I want all Items not return by a given user.</p>
  
  <p>Hint: Items may have may Sales scoped to a User: If an Item has two sales, one returned and one not, I <em>don't</em> want to show that Item.</p>
  
  <pre><code>user_items = user.sold_items.distinct
  goal = user_items.reject {|i| i.returned_sales.first}
  </code></pre>
  
  <p>This does not work because it queries all returned_sales for items, not just the ones scoped to the user.</p>
  
  <hr>
  
  <p><em>Edit:</em> adding Return association <code>has_one :returned_item, through: :sale, source: :item</code> and querying</p>
  
  <pre><code>returned_items = user.returns.map {|r| r.item}
  goal = user_items - returned_items
  </code></pre>
  
  <p>does the trick but is not sexy: single query preferred.</p>