如何按小时分组记录计数

Mat*_*man 4 activerecord ruby-on-rails

这是我的模特:

Interaction.rb

class Interaction < ActiveRecord::Base

  belongs_to :report
  belongs_to :post
  belongs_to :fb_user
  has_one :fb_page
Run Code Online (Sandbox Code Playgroud)

Report.rb

class Report < ActiveRecord::Base

  belongs_to :user

  has_many :page_stats,
    dependent: :destroy
  has_many :interactions,
    dependent: :destroy
  has_many :fb_users,
    through: :interactions
  has_one :fb_page,
    foreign_key: :fb_id,
    primary_key: :fb_page_id
  has_many :posts,
    dependent: :destroy
Run Code Online (Sandbox Code Playgroud)

FbUser.rb

class FbUser < ActiveRecord::Base

  self.primary_key = "id"
  has_many :interactions
Run Code Online (Sandbox Code Playgroud)

我想要做的是按照他们发生的一天中的小时进行交互.我正在寻找1-24(一天中的小时,UTC)的哈希值,并将交互计数按发生时间分组.

这是一个示例返回值:

{{1 => 23},{2 => 7},{n => x}}

基本上,对于第1小时,有23次互动,对于第2小时,有7次.我想每天1到24小时这样做.

交互有一个名为"interaction_time"的列,即交互发生时.谢谢

ush*_*sha 6

对于postgres,

Interaction
.select('EXTRACT(HOUR from interaction_time)')
.group('EXTRACT(HOUR FROM interaction_time)')
.order('EXTRACT(HOUR from interaction_time)')
.count
Run Code Online (Sandbox Code Playgroud)