如何找到每月24个月的捐款总额?

时间:2013-08-29 21:12:01

标签: ruby-on-rails ruby ruby-on-rails-3

从过去两年中抽出捐款后,我试图得出每月捐款总额(共计24笔款项),存储钥匙(每月)和价值(每笔捐款的总和)在一系列哈希中。

这是我到目前为止所得到的:

@donations = Gift.between(Date.today - 2.years, Date.today, :field => gift_date)

@donations.each do |donation|
   #logic here that puts gift_amount into the right month (of the 24 months) 
   # and adds it to the previous balance for that month, ending up with 24 keys 
   # and sum values.
end

我如何在Ruby / Rails中执行此操作?

2 个答案:

答案 0 :(得分:2)

继续@mbratch停止的地方:

donations = Gift.where(:date => (Date.today - 2.years)..Date.today)
Hash[donations.group_by { |d| [d.date.year, d.date.month] }
.map do |year_month, donations|
  [year_month, donations.map(&:amount).reduce(:+)]
end]

答案 1 :(得分:0)

donation_hash = Hash.new(0)

Gift.where(:gift_date => (Date.today - 2.years)..Date.today).each do |donation|
  donation_hash[[donation.gift_date.month, donation.gift_date.year]] += donation.amount
end

这将创建一个哈希,其密钥为[month, year],并为该月/年捐赠的总金额值。可能还有一些其他合适的方法可以创建满足您应用需求的密钥。