I have a “Log” project, each log has a :date, :hours, :description. I am simply trying to determine how many hours I have worked in a week, but am having trouble determining the proper separation of code. Let me know if any further code is needed. Rails 3.
log.rb
def self.days_in_range(from, to)
Log.where(:date => (from.to_date)..(to.to_date))
end
index.html.erb
<% content_for :sidebar do %>
<h4> Sidebar Content </h4>
<ul>
<li>Hours worked this week:
<%= Log.hours_this_week %> # unsure how to call
</li>
<li>Hours worked in total:
<%= Log.sum(:hours) %>
</li>
<li>Most hours worked in a day:
<%= Log.maximum(:hours) %>
</li>
</ul>
<% end %>
logs_helper.rb?
def hours_this_week
today = Time.now
day_of_week = today.wday
sunday = today - day_of_week.days
days = Log.days_in_range(today, sunday)
hours = 0
days.each do |day|
hours += day.hours
end
end
[solved] error
Showing /Users/***/Documents/workspace/***/hours_tracker/hours/app/views/logs/index.html.erb where line #33 raised:
undefined method `hours_this_week' for #<LogsController:0x103b66be8>
Extracted source (around line #33):
30: <h4> Sidebar Content </h4>
31: <ul>
32: <li>Hours worked this week:
33: <%= hours_this_week %>
34: </li>
35: <li>Hours worked in total:
36: <%= Log.sum(:hours) %>
Rails.root: /Users/***/Documents/workspace/***/hours_tracker/hours
[updated] new error
error
ArgumentError in Logs#index
Showing /Users/***/Documents/workspace/***/hours_tracker/hours/app/views/logs/index.html.erb where line #33 raised:
wrong number of arguments (0 for 1)
Extracted source (around line #33):
30: <h4> Sidebar Content </h4>
31: <ul>
32: <li>Hours worked this week:
33: <%= hours_this_week %>
34: </li>
35: <li>Hours worked in total:
36: <%= Log.sum(:hours) %>
Rails.root: /Users/***/Documents/workspace/***/hours_tracker/hours
This is tangential to your question, but I noticed this looking at your
hours_this_weekmethod. I could be wrong, but one little thing you may want to look at here is that yourhours_this_weekmethod is going to return the collection iterated through in youreachstatement (i.e.days), not the product of that statement (the new value ofhours).You could either just add the line:
to the end of this method, or use
injectinstead ofeach:That line would eliminate the need for your
eachstatement and for explicitly returninghoursat the end of yourhours_this_weekmethod.That said, putting the method in
logs_helper.rband calling it with:would be the way to go.