【发布时间】:2013-08-01 19:48:11
【问题描述】:
我正在开发一个应用程序,帮助当地餐馆跟踪每天的工作时间。用户在每个班次结束时通过称为“结帐”的模型输入数据。他们选择与has_many :through => employment 关联的员工,其中雇佣模型是一个连接表。当然,Checkout 是一个令人困惑的术语,但这正是餐厅想要使用的 DSL。
您如何将每位员工在某一天的工作时间分组?当天,该员工的数据库中可能有 2 次结账——一份来自午餐,一份来自晚餐。
我想创建每个员工在给定日期工作的小时数列表,当他们从那天起的小时数可能存储在数据库中的单独结帐中。
Today's Date
Joe Employee
Hours worked: 12
Jill Employee
Hours worked: 4
etc.
当结账不是结账模型的属性而是通过我的雇佣模型关联时,我如何按员工对结账进行分组?本质上,我试图在我的报告助手中做这样的事情:
def checkouts_today
current_user.checkouts.where( :date => Date.today )
end
def employee_hours_today
checkouts_today.where( :employment => Employee.find_by(id: params[:id]) ).sum(:hours)
end
但我无法让它与 has_many :through 关联一起使用。我只能算出如何计算当天的所有小时数,而不是每个员工的总小时数。
以下是相关文件:
- models/checkout.rb - https://gist.github.com/leemcalilly/a2a0578adaf8841d4d5e
- models/employee.rb - https://gist.github.com/leemcalilly/2df5e7fb7db0ac0f602c
models/employment.rb - https://gist.github.com/leemcalilly/d3a028b6effe5f245b2a
helpers/reports_helper.rb - https://gist.github.com/leemcalilly/e2503188bb26df64ad20
查看/payroll_processing.html.erb - https://gist.github.com/leemcalilly/868b1272128e75dc60d0
db/schema.rb - https://gist.github.com/leemcalilly/f9ce764d16161b7b3017
更新: 我可以遍历每个员工并显示他们的结帐:
<% @employees.each do |employee| %>
<% if employee.checkouts.present? %>
<p><%= employee.full_name %></p>
<% employee.checkouts.each do |checkout| %>
<%= checkout.date %>
<%= checkout.shift %>
<%= checkout.hours %>
<% end %>
<% end %>
<% end %>
但是,我不知道如何汇总他们的小时数并在一个块中显示和返回。它返回每个员工姓名下每天的每个结帐。这种逻辑似乎也不应该出现在视图中。
【问题讨论】:
-
我应该使用组方法来执行此操作吗?还是遍历每个员工并显示他们的结账时间?
-
你需要在一行中显示员工的姓名和他的结账时间?
-
我只需要计算员工在某一天的工作时间。但是在任何一天都可能与该员工进行多次结账。员工和结帐与 has_many :through 相关联。我编辑了原始帖子,因为格式令人困惑。
-
为什么 .sum(:hours) 不起作用?
-
我的意思是你得到一个员工一天的所有结账,然后只是总结这些结账的时间。想通过Teamviewer在你的控制台上玩,谁知道,我可能会解决它:)
标签: ruby-on-rails activerecord associations ruby-on-rails-4 has-many-through