In the Item model, you can add a subtotal method:
def subtotal quantity * price end
Assuming you are an Order model as a has_many relationship with Item, you could map
to compile to get a list of prices in the Order model:
def subtotals items.map do |i| i.subtotal end end
Since you work in a Rails environment, you can use the activesupport sum
method to get the total in the Order model:
def total subtotals.sum end
Or if you prefer all together:
def total items.map do |i| i.subtotal end.sum end
You can then use the subtotal on Item and total on Order in your views.
Edit: The view may look like this:
<% for item in @order.items %> <%= item.price %><br/><% end %> <%= @order.total %>
source share