I have a Campaign
model that has_many
items.
Each item has :quantity
and :price
I want to calculate the total price for the Campaign.
I tried with this but won't work.
def campaign_subtotal(campaign)
return campaign.items.sum(item.price * item.quantity)
end
How is this approached?
Thanks a lot
CodePudding user response:
The naive implementation is:
class Campaign < ApplicationRecord
has_many :items
def subtotal
items.sum { |item| item.price * item.quantity }
end
end
You were somewhat close but you need to pass a block to calculate the sum per item. It also makes more sense to make this an instance method rather then a helper.
However if you want to use the subtotal in database queries or you want to display a bunch of campaigns efficiently you would want to calculate it in SQL with a subquery, window query or lateral join. You should also consider recording the price per line (the subtotal) instead of recalculating it all the time.