开发者

How to add up the value of a field in a rails find result

开发者 https://www.devze.com 2023-02-05 18:03 出处:网络
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:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消