# Associated Totals with Eager Loading

**URL:** <https://www.ruby-forum.com/t/associated-totals-with-eager-loading/118876>\
**Category:** Rails\
**Created:** [October 31, 2007, 9:35pm UTC](https://www.ruby-forum.com/t/associated-totals-with-eager-loading/118876 "2007-10-31T21:35:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dacbo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b9e5f3/32.png) [@dacbo](https://www.ruby-forum.com/u/dacbo)\
**Post date:** [October 31, 2007, 9:35pm UTC](https://www.ruby-forum.com/t/associated-totals-with-eager-loading/118876/1 "2007-10-31T21:35:49Z")

</div>

I have the following.

@sales = Sale.find(:all, :include =\> [:sale\_items])

I want totals on the sale items. It works if I code it like this.

@sale\_item\_total = 0  
@sales.each do |sale|  
@sale\_item\_total += @sale.sale\_items.to\_a.sum(&:price)  
end  
@sale\_item\_total

The problem is my real world project has nested includes on several  
models  
and I want totals on all of them so I’m looking for a rails way to  
access a  
collection of all the associated sale items in an instance variable like  
@sale\_items without needing to reference each @sale first.

I could pull them out like this but isn’t there a better way?

@sale\_items = []  
@sales.each do |sale|  
sale.sale\_items.each do |sale\_item|  
@sale\_items \<\< sale\_item  
end  
end  
@sale\_item\_total = @sale\_items.to\_a.sum(&:price)

---

<div class="post-metadata">

**Author:** ![dacbo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b9e5f3/32.png) [@dacbo](https://www.ruby-forum.com/u/dacbo)\
**Post date:** [October 31, 2007, 11:45pm UTC](https://www.ruby-forum.com/t/associated-totals-with-eager-loading/118876/2 "2007-10-31T23:45:02Z")

</div>

Does Sale.sum(:price, :include =\> [:sale\_items]) do what you want ?

Fred
