Ruby on Rails:本周工作时间

时间:2011-06-16 16:57:03

标签: ruby-on-rails ruby ruby-on-rails-3

我有一个“Log”项目,每个日志都有:date,:hours,:description。我只是想确定我在一周内工作了多少小时,但我在确定代码的正确分离方面遇到了麻烦。如果需要任何进一步的代码,请告诉我。 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

[已解决] 错误

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

full trace

[已更新] 新错误

错误

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

2 个答案:

答案 0 :(得分:0)

假设您的index.html.erb文件位于app/views/logs文件夹中,您可以直接致电hours_this_week

<%= hours_this_week %>

答案 1 :(得分:0)

这与您的问题相关,但我注意到这会查看您的hours_this_week方法。我可能错了,但你可能想看一下这个小问题是你的hours_this_week方法会在你的each语句(即days)中返回迭代的集合,不是该陈述的产物(hours的新值)。

您可以添加以下行:

 hours

到此方法的结尾,或使用inject代替each

# The initial "hours" declaration is no longer necessary,
# because inject returns its result, rather than the 
# collection it is iterating through.

days.inject(0) {|hours, day| hours += day.hours }

该行不再需要您的each声明,也不会在hours方法结束时明确返回hours_this_week

也就是说,将方法放在logs_helper.rb中并用以下方法调用:

<%= hours_this_week %>

将是要走的路。