I have the following code in a view that lists all customers and the total amount of each customer's orders.
The relationship between the entity types Customer, Order and OrderItem is: Customer-1:n-Order-1:n-OrderItem
view index.rb
<% @customers.each do |c| %>
<tr>
<td id="name"><%= c.name %>
<td id="cus_total"><%= c.orders.map(&:order_total_amount).sum %>
</tr>
customers_controller.rb
@customers = Customer.find(:all)
model orders.rb
def order_total_amount
orderitems.sum("amount")
end
I now want to print the total amount of all orders by all customers in the first row of the table. Obviously, I don't want to query the DB again for this task, since the total amount is just the sum of all items in column "cus_total". If I'd want to print the total amount at the bottom of the table, I'd just do
<% @customers.each do |c| %>
<tr>
<td id="name"><%= c.name %>
<td id="cus_total"><%= total += c.orders.map(&:order_total_amount).sum %>
</tr>
<% end %>
<tr>
<td>Total</td>
<td><%= total %></td>
</tr>
But what do I do in Rails 4 when I want to print the total amount at the top of the table without querying the database again?