0

我正在尝试计算每个月数据库中的记录数。但是有几个月没有任何记录,我也想将它们添加到我的数组中

@activity = Activity.find(params[:id])
records_by_month = @activity.records.max_12_months.group_by{ |t| t.happened.beginning_of_month }
hori = Array.new
verti = Array.new
records_by_month.sort.each do |month, recs|
  hori.push(month.strftime('%B'))
  verti.push(recs.count)
end

这是 records_by_month 的样子:

#<OrderedHash {Tue, 01 Jan 2013=>[#<Record id: 37, details: "",
happened: "2013-01-09", duration: nil, activity_id: 21, created_at: "2013-04-11 14:31:30",
updated_at: "2013-04-11 14:31:30", price: 15.0>], Fri, 01 Mar 2013=>
[#<Record id: 36, details: "", happened: "2013-03-04", duration: nil,
activity_id: 21, created_at: "2013-04-11 14:31:12", updated_at: "2013-04-11 14:31:12", price: 15.0>],
Thu, 01 Nov 2012=>[#<Record id: 38, details: "", happened: "2012-11-29",
duration: nil, activity_id: 21, created_at: "2013-04-11 14:31:51",
updated_at: "2013-04-11 14:31:51", price: 15.0>]}>

知道如何将月份名称添加到 hori,并将 0 添加到没有记录的每个月的 verti 吗?

4

2 回答 2

0

这是对您的问题的提示,而不是完整的解决方案:

require 'date'

h = {"Tue, 01 Jan 2013" =>[Record_id: 37, details: "",
happened: "2013-01-09", duration: nil, activity_id: 21, created_at: "2013-04-11 14:31:30",
updated_at: "2013-04-11 14:31:30", price: 15.0], "Fri, 01 Mar 2013" =>
[Record_id: 36, details: "", happened: "2013-03-04", duration: nil,
activity_id: 21, created_at: "2013-04-11 14:31:12", updated_at: "2013-04-11 14:31:12", price: 15.0],
"Thu, 01 Nov 2012" =>[Record_id: 38, details: "", happened: "2012-11-29",
duration: nil, activity_id: 21, created_at: "2013-04-11 14:31:51",
updated_at: "2013-04-11 14:31:51", price: 15.0]}

hori = {}
verti = {}

h.each {|k,v| hori[Date.parse(k).strftime('%B')] = v}
p hori

Date::MONTHNAMES.compact.map {|m| verti[m]=0 unless hori.keys.include? m}
p verti

输出:

{"January"=>[{:Record_id=>37, :details=>"", :happened=>"2013-01-09", :duration=>nil, :activity_id=>21, :created_at=>"2013-04-11 14:31:30", :updated_at=>"2013-04-11 14:31:30", :price=>15.0}], "March"=>[{:Record_id=>36, :details=>"", :happened=>"2013-03-04", :duration=>nil, :activity_id=>21, :created_at=>"2013-04-11 14:31:12", :updated_at=>"2013-04-11 14:31:12", :price=>15.0}], "November"=>[{:Record_id=>38, :details=>"", :happened=>"2012-11-29", :duration=>nil, :activity_id=>21, :created_at=>"2013-04-11 14:31:51", :updated_at=>"2013-04-11 14:31:51", :price=>15.0}]}

{"February"=>0, "April"=>0, "May"=>0, "June"=>0, "July"=>0, "August"=>0, "September"=>0, "October"=>0, "December"=>0}
于 2013-04-11T20:40:37.673 回答
0

好的(为测试稍作更改)......这样的事情怎么样?

ALL = [%w{
  January February March
  April   May      June
  July    August   September
  October November December
}, [0] * 12].transpose
hori = Hash[ALL]
verti = Hash[ALL]
{'January' => 1, 'March' => 5}.each do |month, recs|
  hori[month] = :test
  verti[month] = recs
end
p hori.sort.map(&:last)  # => [0, 0, 0, 0, :test, 0, 0, :test, 0, 0, 0, 0]
p verti.sort.map(&:last) # => [0, 0, 0, 0, 1, 0, 0, 5, 0, 0, 0, 0]
于 2013-04-11T19:59:00.450 回答