Ruby on rails 如何按天分组并将计算属性与GroupDate相加?

Ruby on rails 如何按天分组并将计算属性与GroupDate相加?,ruby-on-rails,chartkick,Ruby On Rails,Chartkick,我正在使用chartkick在rails应用程序中呈现图表。我想使用groupdate查询过去7天的数据,如果没有一天,则得到0 我知道我可以这样使用它: project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").count project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(&:d

我正在使用
chartkick
在rails应用程序中呈现图表。我想使用
groupdate
查询过去7天的数据,如果没有一天,则得到0

我知道我可以这样使用它:

project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").count
project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(&:duration_sec)
TimeEntry.from(time_entries.select('(EXTRACT(EPOCH FROM (UPPER(time) - LOWER(time)))) AS duration, created_at')).group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(:duration)
但是,我不想得到找到的记录数,而是想得到计算字段的总和:

class TimeEntry < ActiveRecord::Base
  def duration_sec
    (self.time.end - self.time.begin).to_i
  end
end
我想得到那天的
duration\u sec
总数。因此,我想通过
DateGroup
完成类似的任务:

project.time_entries.group_by{ |a| a.created_at.to_date.to_s }.map { |k, v| { k => v.sum(&:duration_sec) } }
我也试过这样的方法:

project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").count
project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(&:duration_sec)
TimeEntry.from(time_entries.select('(EXTRACT(EPOCH FROM (UPPER(time) - LOWER(time)))) AS duration, created_at')).group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(:duration)

但我得到一个参数错误异常。

据我所知,ActiveRecord::Calculations#sum无法调用自定义方法。同时,这可能是一个解决办法

TimeEntry.unscoped.select(:duration_sec)
  .from(project.time_entries.select('time_end - time_begin AS durations_sec, created_at'))
  .group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(:duration_sec)

通过@cozyconemotel answer,我成功地得到了我所需要的:

project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").count
project.time_entries.group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(&:duration_sec)
TimeEntry.from(time_entries.select('(EXTRACT(EPOCH FROM (UPPER(time) - LOWER(time)))) AS duration, created_at')).group_by_day(:created_at, last: 7, format: "%a\n%d %b").sum(:duration)

这以秒为单位提取时间戳,而不是字符串格式,这是我所需要的

time是postgresql中的tsrange,我想这就是为什么这对我不起作用的原因,你知道如何从postgres中的范围类型中获取
begin
end
值吗?好的,我使用的是
upper(time)-lower(time)
这似乎很有效。但是,该值的格式是类似于
hh:mm:ss
的字符串,我实际上需要它作为浮点值