Home > Blockchain >  How to separate data of the same time(hour) in ruby on rails?
How to separate data of the same time(hour) in ruby on rails?

Time:07-27

I have a step table that contains values ​​obtained over the course of a day. I used this to group several values ​​from the same day:

MonitorRecord.where(user_id: id).group_by { |item| item.registered_at.to_date }

I did this to calculate the total number of steps for migrating data from multiple users. It's working fine and the answer is a very easy hash to work with.

Result Hash

I need to do the same for a heart rate table, only this time, separating by hour and no longer by day. I need this separate data to calculate an hourly average.

Is it possible to make a request as in the previous example, but now separating the data by time (hour)?

The registered_at field has the following format: 2019-05-31 18:10:57

I need to access all the data and not group it into a single one. Any help is appreciated.

CodePudding user response:

You use strftime

registerd_at.strftime(%H:%M:%S) // 2019-05-31 18:10:57 => 18:10:57

CodePudding user response:

You can use this as this will return the data separated by hour and then you can do whatever calculation you need. As this will return you a hash like this {"hour": [rows]}

MonitorRecord.where(user_id: id).group_by { |item| item.registered_at.strftime(%H) }
  • Related