从过去两年中提取捐款后,我试图得出每月捐款的总和,将键(每个月)和值(每个月的捐款总和)存储在哈希数组中。我希望键是数字 1 到 24(1 是两年前,24 是本月),如果给定月份没有捐款,则该月的值将为零。作为 Ruby/Rails 中的哈希数组,我将如何做到这一点?
这是我的变量,其中已经有捐款。
donations = Gift.where(:date => (Date.today - 2.years)..Date.today)
从过去两年中提取捐款后,我试图得出每月捐款的总和,将键(每个月)和值(每个月的捐款总和)存储在哈希数组中。我希望键是数字 1 到 24(1 是两年前,24 是本月),如果给定月份没有捐款,则该月的值将为零。作为 Ruby/Rails 中的哈希数组,我将如何做到这一点?
这是我的变量,其中已经有捐款。
donations = Gift.where(:date => (Date.today - 2.years)..Date.today)
以下为您提供了一个哈希,带有键 '2013/09" 等...
monthly_donations = {}
date = Time.now
while date > 2.years.ago do
range = date.beginning_of_month..date.end_of_month
monthly_donations[ "{#date.year}/#{date.month}" ] = Giftl.sum(:column, :conditions => {created_at >= range})
date -= 30.days
end
要选择该时间跨度内的记录,这应该足够了:
donations = Gift.where("date >= #{2.years.ago}")
你也可以这样做:
donations = Gift.where("date >= :start_date AND date <= :end_date",
{start_date: 2.years.ago, end_date: Time.now} )
另见:2.2.1“占位符条件” http://guides.rubyonrails.org/active_record_querying.html
要汇总数据库记录中的列,您可以执行以下操作:
sum = Gift.sum(:column , :conditions => {created_at >= 2.years.ago})
首先,我们需要一个函数来查找与当前时间的月差。
def month_diff(date)
(Date.current.year * 12 + Date.current.month) - (date.year * 12 + date.month)
end
然后我们遍历@donation,假设 :amount 用于存储每笔捐赠的价值:
q = {}
@donations.each do |donation|
date = month_diff(donation.date)
if q[date].nil?
q[date] = donation.amount
else
q[date] += donation.amount
end
end
我找到了一个涵盖所有基础的好解决方案——@user1185563 的解决方案在没有捐款的情况下几个月都没有带来,@Tilo 调用了数据库 24 次,但我非常感谢这些想法!我确信这可以更有效地完成,但我创建了包含 24 个元素的散列(键:每个月的开始,值:0),然后遍历捐赠并将其金额添加到适当位置的散列中。
def monthly_hash
monthly_hash = {}
date = 2.years.ago
i = 0
while date < Time.now do
monthly_hash["#{date.beginning_of_month}"] = 0
date += 1.month
i += 1
end
return monthly_hash
end
@monthly_hash = monthly_hash
@donations.each do |donation|
@monthly_hash["#{donation.date.beginning_of_month}"] += donation.amount
end