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)