I’m displaying a list of items which have a priceattribute in an HTML table.
What is the right way of getting the total price add the end of the table (and where should the calculation happen)?
I can think of 3 obvious ways, but I don’t know which one is the most “orthodoxic”
1- in the controller
@items = Item.all
@item_total = @items.sum(:price)
and I simply display @item_totalin my last line
2- in the view, on the last line
<%= @items.sum(:price) %>
But I’m not sure that it’s OK to do this in a view (it works, but is it OK?)
3- in the view, add this on the last line
<%= @items.inject(0){|s, e| s + e.price} %>
But this doesn’t feel right to add this kind of logic in the view.
So which one of these is the right one? Or is there another way I’m missing?
try this way
and
@item_totaluse in yourviewfileUpdate
If you use this like
indexaction then you can do this waybut if you want to only
item_totalthen don’t pass two queries for sum you can do like