Reputation: 4927
I am making a timesheet, but i have problems. I want it to look like this:
projects |Monday Tuesday Wednesday Thursday Friday Saturday Sunday
development| 3:50 4:00 5:00 3:00 0:00 0:00 0:00
Testing | 0:00 0:00 0:00 2:00 4:00 0:00 0:00
Lanch | 0:00 0:00 0:00 0:00 1:00 6:00 0:00
Every project has_many logs with hours as a field.
I did this query:
@log_week_project = current_user.logs.where(:log_date => (Time.now.beginning_of_week + 1.second)..(Time.now.end_of_week - 1.second)).group("project_id").group("date(log_date)").sum(:hours)
And get this:
<OrderedHash {[2, "2011-05-24"]=>31800.0, [1, "2011-05-24"]=>10200.0, [1, "2011-05-23"]=>25200.0, [1, "2011-05-26"]=>19800.0}>
The key in the hash is an array with the project_id @ [0] and log_date @ [1]. The value is the hours.
I do this in my view:
<% for project in @projects do %>
<%= project.name %>
<% @log_week_project.map do |key,hours|%>
<% if key[0] == project.id %>
<%= time_diff(hours)%>
<% end %>
<% end %>
<% end %>
This gives me the project hours on each date, but if there is a date with no hours there is no output and the table gets wrong.
If there is no hours on wednesday the thursday hours ends up in the wednesday column.
Any tips on how to do this? Perhaps there is a better way?
SOLUTION:
Thanks for replies and comments. The solution was:
<% for project in @projects do %>
<%= project.name %>
<% @dates.each do |date| %>
<% hours = @log_week_project.detect { |key| key[0][0].to_i == project.id && key[0][1].to_time.strftime('%a') == date.to_time.strftime('%a')}%>
<%= hours ? time_diff(hours[1]) : "0:00"%>
<% end %>
<% end %>
Where @dates is an array of the dates in the timerange. Now refactoring... ; )
Upvotes: 1
Views: 885
Reputation: 206
you can do this:
<% for project in @projects do %>
<%= project.name %>
<% (1..7).each do |day| %>
<% date = "2011-05-#{22 + day}" #please modify this, this is only to keep the example simple %>
<% hours = @log_week_project.detect{|key| key[0] == project && key[1] == date } %>
"<%= hours ? time_diff(hours) : "" %>
<% end %>
<% end %>
<% end %>
<% end %>
next, refactor this to put all the logic in a helper. Hope, that helps
Upvotes: 1
Reputation: 2107
In your database you may have 0 as default for all hours, that way it can't be blank.
But if you storing hours in logs, then you can't do above. In that case, use
time_diff(hours).present? ? time_diff(hours) : 0
Or else you may use anything else than 0, that way tables will not disturbed.
Upvotes: 0