我有一个名为Receipt的模型,它有以下内容:
我有一个包含许多收据的数据库,例如:
收据1
收据2
收据3
收据4
...
收据123
如何显示以下内容:
{2012 => {1 => 76},2013 => {2 => 92.23,3 => 34.43,...}}
答案 0 :(得分:1)
以下应该工作
receipts = Receipt.find_by_sql("SELECT MONTH(date_of_purchase) AS month,
YEAR(date_of_purchase) AS year, SUM(total_value) as sum
FROM receipts GROUP BY year, month")
receipts_hash = {}
receipts.each do |receipt|
receipts_hash[receipt.year] = {} unless receipts_hash[receipt.year]
receipts_hash[receipt.year][receipt.month] = receipt.sum
end