Rails method of calculating intermediate and final

Context: I have 2 Order and Item models.

I want to calculate the subtotal of an item based on item.quantity * item.price While this is being done in the view (but not in the appropriate place).

<%= number_to_currency(item.quantity * item.price) %> 

I also need to calculate the order amount, but I'm stuck. I do not have a column for this. What is the best approach? Use a model? Assistant or supervisor?

At the moment, I managed to do intermediate work through the order helper

 def item_subtotal(item) item_subtotal = item.quantity * item.price end 

Working solution:

Product Model

 def subtotal price * quantity end 

In the rendering view <%= item.subtotal %>

Order model

 def total_price total_price = items.inject(0) { |sum, p| sum + p.subtotal } end 

Order # show view render <%= number_to_currency(@order.total_price) %>

+4
source share
3 answers

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 %> 
+7
source

Since this is the functionality of the model (you want to calculate something from an element that is self-referential), the model itself is more suitable, so you can easily use

 item.subtotal 
0
source

You can show item_subtotal with

and for the total amount you can calculate it

total_price = @ order.items.to_a.sum {| item | total = item.product.price * item.quantity}

I think this will work for you.

0
source

All Articles