切片/映射有序哈希
我正在为我的办公室编写一个“打卡时钟”应用程序。我正在开发“时间卡”视图的控制器,该视图应列出给定一周的用户打卡次数,以及每日总计,然后添加该周的总计。我已经弄清楚如何使用切片/地图获取所有打孔之间的时间差异,我的问题是,当我尝试在有序哈希(按天分组)上执行此操作时,我得到 # 的未定义方法“created_at”,我知道我一定在某个地方遗漏了一些语法,非常感谢您的帮助...
这是我的控制器...
请注意,如果我在 @punches 上调用 @in_out_lenghts,这会起作用并为我提供本周的总数,但 @punches_days 给出意思是错误,因此我无法保持运行计数......
def mytimecard
@week = params[:week].to_s
if @week == "lastweek"
@punches = Punch.lastweek.where("user_id = ?", params[:user])
else
@punches = Punch.thisweek.where("user_id = ?", params[:user])
end
@punches_days = @punches.group_by { |t| t.created_at.beginning_of_day}
if @punches.count%2 == 0
@in_out_lengths = @punches_days.each_slice(2).map { |a|(a[1].created_at).round(15.minutes) - (a[0].created_at).round(15.minutes) }
@total = ((@in_out_lengths.inject(:+))/60/60)
else
@total = "Can Not Calculate, Odd Number of Punches"
end
respond_to do |format|
format.html # timecard.html.erb
format.json { render :json => @punches }
end
end
I am writing a "Punch Clock" application for my office.. I am working on the controller for the "TIme Card" view which should list a users punches for a given week, and total DAILY then add the TOTAL for the week. I have figured out how to get the time diff between all of the punches with slice/map, my issue is that when I try to do this on the ordered hash (grouped by days) I get undefined method `created_at' for #, I know I must be missing some syntax somewhere, your help is greatly appreciated...
Here is my controller...
Note that if i call @in_out_lenghts on @punches, this works and gives me the total for the week, but @punches_days gives me an error, therefore I can not keep a running tally....
def mytimecard
@week = params[:week].to_s
if @week == "lastweek"
@punches = Punch.lastweek.where("user_id = ?", params[:user])
else
@punches = Punch.thisweek.where("user_id = ?", params[:user])
end
@punches_days = @punches.group_by { |t| t.created_at.beginning_of_day}
if @punches.count%2 == 0
@in_out_lengths = @punches_days.each_slice(2).map { |a|(a[1].created_at).round(15.minutes) - (a[0].created_at).round(15.minutes) }
@total = ((@in_out_lengths.inject(:+))/60/60)
else
@total = "Can Not Calculate, Odd Number of Punches"
end
respond_to do |format|
format.html # timecard.html.erb
format.json { render :json => @punches }
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
group_by 将返回天数和拳数的哈希值。
执行each_slice和map将产生某种数组,但可能不是你的意思。
您可能想计算出拳的次数并调用类似这样的内容
这将导致日期=> punches_count 格式,至少对于 mysql 来说是这样。
group_by will return a hash of days and punches.
doing an each_slice and a map will result in some sort of array, but probably not what you meant.
You may have meant to count the number of punches and call something like this
This would have resulted in the date => punches_count format, at least with mysql.