I am creating a Rails 3.2 web app and in this app I am collecting and displaying time reports. I have a query that looks like this:
@reports = Timereport.where("backend_user_id = ?", user.id).group("id, date(created_at)").created_between(from, to).order("date(created_at) desc").select("id, date (created_at) as date, sum(total_time) as seconds")
Which outputs this:
[#<Timereport id: 370>, #<Timereport id: 367>, #<Timereport id: 368>, #<Timereport id: 369>]
Each object contains date and seconds which can be accessed like this:
<% @reports.each do |report| %>
<%= report[:date] %>
<%= report[:seconds] %>
<% end %>
What I really need to be able to do is to group by days to get total amount of seconds per day:
I tried this:
<% output = @reports.map { |f| [f.date, f.seconds] } %>
Which gave me this result where the dates are seperate. I need to group the dates so that I can get the total amount of seconds per day.
[["2014-06-18", "3600"], ["2014-06-17", "3600"], ["2014-06-17", "3600"], ["2014-06-17", "3600"]]
So in other words. I need this result:
[["2014-06-18", "3600"], ["2014-06-17", "10800"]]
How can I achieve this?
You can do it with next code:
@reports.group_by { |x| x.date }.map { |date, record|
[date, record.map(&:seconds).map(&:to_i).reduce(:+).to_s]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With