4

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?

asked Jun 18, 2014 at 10:51
0

1 Answer 1

6

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]
}
answered Jun 18, 2014 at 11:17
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.