【问题标题】:Rails group by hour of the day for created_at column对于 created_at 列,Rails 按一天中的小时分组
【发布时间】:2016-04-01 16:01:06
【问题描述】:

我有一个Subscribe Model,想按一天中的时间分组。我检查过 rails group records by dates of created_atrails - group by day as well as hour 但没有运气!

2.3.0 :175 > Subscribe.find 13
  Subscribe Load (0.9ms)  SELECT  "subscribes".* FROM "subscribes" WHERE "subscribes"."id" = $1 LIMIT 1  [["id", 13]]
 => #<Subscribe id: 13, user_id: 7, publisher_id: 5, created_at: "2015-11-23 00:37:49", updated_at: "2016-03-22 08:04:31", subscription_id: "2"> 

关于应用其他解决方案

2.3.0 :174 > Subscribe.where("DATE_PART('hour', created_at) = ?", 13)
  Subscribe Load (1.0ms)  SELECT "subscribes".* FROM "subscribes" WHERE (DATE_PART('hour', created_at) = 13)
 => #<ActiveRecord::Relation []> 

为了实现这一点,我使用了groupdate

graph_data =  Subscribe.group_by_hour_of_day(:created_at, format: "%-l %M %P", time_zone: "Kolkata",range: start_date.to_datetime..end_date.to_datetime).count

 => {"12 00 am"=>0, "1 00 am"=>0, "2 00 am"=>0, "3 00 am"=>0, "4 00 am"=>0, "5 00 am"=>1, "6 00 am"=>1, "7 00 am"=>0, "8 00 am"=>0, "9 00 am"=>0, "10 00 am"=>0, "11 00 am"=>0, "12 00 pm"=>1, "1 00 pm"=>1, "2 00 pm"=>0, "3 00 pm"=>0, "4 00 pm"=>0, "5 00 pm"=>0, "6 00 pm"=>0, "7 00 pm"=>0, "8 00 pm"=>0, "9 00 pm"=>0, "10 00 pm"=>0, "11 00 pm"=>0} 

但是对于订阅 13,在 created_at (2015-11-23 00:37:49) 有一条记录,但它返回为 0

任何帮助将不胜感激!!!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    试试

    Subscribe.all.group_by{ |s| s.created_at.hour }
    

    【讨论】:

      【解决方案2】:

      Groupdate Gem 有一个小问题。为了解决这个问题,我必须将created_at 转换为相应的time zone

      range: start_date.to_datetime.in_time_zone(time_zone)..end_date.to_datetime.in_time_zone(time_zone).end_of_day).count
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 2021-11-06
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多