How to add up the value of a field in a rails find result
I do:
@deals = Deal.find(:all)
I use @deals for a number of things. Every deal has a value field (how much money the deal is worth). I want to know the combined value of all deals. I have this now:
@deals.each { |deal| @total_value += deal.value }
But I'm hoping 开发者_开发问答and guessing ActiveRecords have a better way to do this? Is there?
Try following:-
@deals_value = Deal.sum(:value)
Thanks....
Assuming that you want to keep Deal.find(:all), and you want to use @deals to find the sum without a loop, try the following
@deals.sum(&:value)
精彩评论