Reputation: 935
I am using mongoid with rails4, I need group by result for supplying charts (statistics screen) for that I am using below code.
@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}
it will give like
{
"1-1-2014" => 2,
"3-1-2014" => 1,
"4-1-2014" => 2,
"6-1-2014" => 4
}
but I want like below
{
"1-1-2014" => 2,
"2-1-2014" => 0,
"3-1-2014" => 1,
"4-1-2014" => 2,
"5-1-2014" => 0,
"6-1-2014" => 4
}
any one suggest how to simplify above query also.
Thanks Prasad.
Upvotes: 3
Views: 7169
Reputation: 5535
You can try something like this:
@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
I haven't tested it so it can have some issue
Upvotes: 9