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

わかりました(テスト用に少し変更)...次のようなものはどうですか?

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 に答える