2

I have a Subscribe Model and want to group by hour of day. I checked with rails group records by dates of created_at and rails - group by day as well as hour But no luck!.

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"> 

on applying the other solution

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 []> 

To achieve this I used 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} 

but for Subscribe 13 there is an record at created_at (2015-11-23 00:37:49) but it return as 0

Any help would be appreciated!!!

Community
  • 1
  • 1
Gupta
  • 8,882
  • 4
  • 49
  • 59

2 Answers2

5

try

Subscribe.all.group_by{ |s| s.created_at.hour }
Oleh Sobchuk
  • 3,612
  • 2
  • 25
  • 41
0

There was a little gotch with Groupdate Gem. In order to fix this I have to convert created_at to respective 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
Gupta
  • 8,882
  • 4
  • 49
  • 59