title: ActiveRecord query to sum over joins
body: <p>I want to get the sum of the receipt items that are in a particular budget (same title) and from the current query I'm getting to many record and obvious wrong sum of amounts from the receipt items.</p>
  
  <p>My current attempt is looking like that in ActiveRecord (AR):</p>
  
  <pre><code>ReceiptItem.includes(donation: [:budgets]).joins(:donation, :receipt).where(budgets: {title: "Some title 2015"}).sum(:amount)
  </code></pre>
  
  <p>and my SQL attempt was looking like that (its also wrong):</p>
  
  <pre><code>-- want to test just the outcome its not actually not summing up the amounts
  SELECT "receipt_items"."amount"
  FROM
    "receipt_items" INNER JOIN "donations" ON "donations"."id" = "receipt_items"."donation_id"
      RIGHT JOIN "receipts" ON "receipts"."receipt_id" = "receipt_items"."receipt_id"
      LEFT OUTER JOIN "budgets" ON "budgets"."donation_id" = "donations"."id"
  WHERE "budgets"."title" = 'Some title 2015';
  </code></pre>
  
  <h3>Why I'm getting double records although I've joined the tables and set also the condition?</h3>
  
  <p>Here is the ER modell to understand the problem.
  <a href="https://i.stack.imgur.com/zesxl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zesxl.png" alt="ER model"></a></p>
  
  <p>And here's the AR Assoziations:</p>
  
  <pre><code>class Budget &lt; ActiveRecord::Base
    belongs_to :donation
  class Donation &lt; ActiveRecord::Base
      has_many :receipt_items
      has_many :budgets
  class ReceiptItem &lt; ActiveRecord::Base
    belongs_to :donation
  </code></pre>