Dur*_*sad 3 mongodb mongoid ruby-on-rails-4
我正在使用带有rails4的mongoid,我需要按结果分组提供图表(统计屏幕),我正在使用下面的代码.
@comments_stats = {}
comments_data = Comment.where(:created_at.lte => Date.today-10.days).group_by {|d| d.created_at.to_date }
comments_data.map{ |a| @comments_stats[a[0].strftime("%d-%m-%y")] = a[1].size}
Run Code Online (Sandbox Code Playgroud)
它会给出类似的
{
"1-1-2014" => 2,
"3-1-2014" => 1,
"4-1-2014" => 2,
"6-1-2014" => 4
}
Run Code Online (Sandbox Code Playgroud)
但我想在下面
{
"1-1-2014" => 2,
"2-1-2014" => 0,
"3-1-2014" => 1,
"4-1-2014" => 2,
"5-1-2014" => 0,
"6-1-2014" => 4
}
Run Code Online (Sandbox Code Playgroud)
任何人都建议如何简化以上查询.
谢谢普拉萨德.
你可以尝试这样的事情:
@comments_stats = {}
last_date = Date.today - 10.days
comments_data = Comment.where(:created_at.lte => last_date).group_by {|d| d.created_at.strftime("%d-%m-%y")}
first_date = Date.parse(comments_data.keys.min)
(first_date..last_date).map do |n_date|
day = n_date.strftime("%d-%m-%Y")
@comments_stats[day] = comments_data[day] ? comments_data[day].size : 0
end
Run Code Online (Sandbox Code Playgroud)
我没有测试它,所以它可能有一些问题
| 归档时间: |
|
| 查看次数: |
5907 次 |
| 最近记录: |