Reputation: 7003
<% @cart.items.each do |item| %>
<div class="holder">
<div class="image"><%= link_to (image_tag (item.product.avatar.url(:thumb))), item.product %></div>
<div class="title"><%= link_to item.product.title, item.product %></div>
<div class="count"><%= item.count %></div>
<div class="price"><%= number_to_currency(item.product.price, :unit => '€ ') %></div>
<div class="description"><%= item.product.description.truncate(110).html_safe %></div>
</div>
<% end %>
<div class="total">Total price: @price</div>
I'd like to get the total sum of item.product.price
column for each cart
and then display it at the end of the carts list. How can that be done?
Upvotes: 4
Views: 1074
Reputation: 9622
You can use arel to achieve this, it avoids loading the items and their products so you wont be hit with as many queries as you have items in your cart:
@cart.items.joins(:product).sum("products.price")
This will lead to a query like:
SELECT SUM(products.price) AS sum_id
FROM `items`
INNER JOIN `products` ON `products`.`id` = `items`.`product_id`
WHERE `items`.`cart_id` = 1
Upvotes: 5