Reputation: 1527
I have a model which contains items for sale. The model is mirroring an API, so I can't change it's structure.
In this model I have the fields price
and sold_quantity
.
It doesn't seem right to iterate through the query with a loop.
current_user.items.each do |item|
total += item.price * item.sold_quantity
end
Is there a way to get the same total using only ActiveRecord? Like .sum(:price)
but multiplying by sold_quantity
?
Upvotes: 1
Views: 860
Reputation: 1050
One way you could approach this would be to move this logic into the Item class:
class Item < ActiveRecord::Base
...
def total
self.price * self.sold_quantity
end
def self.sold_value
all.map{|a| a.total}.sum
end
end
Here each instance of item is calculating it's own total, and a class method allows you get the sold value on any collection of items.
@user.items.sold_value
Upvotes: 1
Reputation: 5105
You can do this:
current_user.items.sum { |item| item.price * item.sold_quantity }
I hope this help you.
For more information sum in AR
Upvotes: 1
Reputation: 106027
You probably want this:
current_user.items
.select('items.*, items.price * items.sold AS total')
.all
Or, if you want the totals and nothing else:
current_user.items.pluck('items.price * items.sold')
Upvotes: 3