I'm using chartkick
to render charts in my rails app. And I'd like to use groupdate
to query the data for the last 7 days getting 0 if a day is not present.
I know I can use it like this:
project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").count
However, I don't want to get the count of the records found, I want instead to get the sum of a calculated field:
class TimeEntry < ActiveRecord::Base
def duration_sec
(self.time.end - self.time.begin).to_i
end
end
so if there were 4 records on 25th March instead of getting:
{"20 Mar"=>0, "21 Mar"=>0, "22 Mar"=>0, "23 Mar"=>0, "24 Mar"=>0, "25 Mar"=>4, "26 Mar"=>0}
I'd like to get the total sum of duration_sec
for that day. So I want to accomplish something like this with DateGroup
:
project.time_entries.group_by{ |a| a.created_at.to_date.to_s }.map { |k, v| { k => v.sum(&:duration_sec) } }
I also tried something like this:
project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(&:duration_sec)
but I get an argument error exception.