How to sum columns in rails?
<% @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 would like to get the total column amount item.product.pricefor each cart, and then display it at the end of the cart list. How can I do that?
+4
1 answer
You can use isl to achieve this, it avoids loading items and their products, so you won’t be hit as many queries as you have in the basket:
@cart.items.joins(:product).sum("products.price")
This will result in 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
+5