【发布时间】:2021-11-13 05:26:11
【问题描述】:
您好,我正在为自己构建一个小型 Rails 会议应用程序。我有一张名为 Meetings 的表格,有 5 列
name:string start_date:datime end_date:datetime duration:integer overtime:integer
我的问题是,是否有比我现在做的更好的计算加班时间的方法?
持续时间是每天 start_date 和 end_date 之间的总时间,每天可以有多个会议。
加班时间是每天的总持续时间减去 7 小时 25 分钟(26700 秒),任何每天超过 7.25 的会议总持续时间都是加班时间。 我得到了我想要的结果(见下图),但我想知道是否有更好的方法?我在 index.html.erb 中使用了 if 语句。得到我想要的结果,因为保存到数据库的加班数据不是我需要的实际加班数据。
从下图中,我通常只希望将“22 分钟和 40 分钟”保存为整数。我还想展示每周的总加班时间,这就是为什么我认为我的方式行不通的原因。他们是更好的方法吗?
在此先感谢您的任何意见。
Meeting.rb 模型文件中的两个计算列持续时间和加班时间
class Meeting < ApplicationRecord
#callbacks save to db
before_save :set_duration
before_save :daily_total_ot
#calculate duration
def set_duration
self.duration = (end_date - start_date).to_i
end
#Calculate total duration for each day
def daily_total_duration
Meeting.where("start_date >= ? AND end_date < ?", self.start_date.beginning_of_day, self.start_date.end_of_day).sum(:duration)
end
#calculate total overtime for each day
def daily_total_ot
self.overtime = Meeting.where("start_date >= ? AND end_date < ?", self.start_date.beginning_of_day, self.start_date.end_of_day).sum(:duration) - 26700.to_i
end
end
在我看来会议 .index.html.erb 我有
<h1>Meetings</h1><%= Time.zone.now.strftime('%d-%b-%Y') %>
<table class="table">
<thead class="thead-dark">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Duration</th>
<th>Duration Time</th>
<th>Daily Total <br>Duration</th>
<th>overtime saved</th>
<th>Real OT</th>
<th>Show</th>
<th>Edit</th>
<th>Destroy</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @meetings.each do |meeting| %>
<tr>
<td><%= meeting.name %></td>
<td><%= meeting.start_date.strftime("%d-%b-%Y %I:%M %p") %></td>
<td><%= meeting.end_date.strftime("%d-%b-%Y %I:%M %p") %></td>
<td><%= meeting.duration %></td>
<td><%= Time.at(meeting.daily_total_duration).utc.strftime("%H hours and %M minutes ") %></td>
<td><%= meeting.daily_total_ot %></td>
<% if (meeting.daily_total_duration) > 26700 %>
<td><%= Time.at(meeting.daily_total_ot).utc.strftime("%H hours and %M minutes ") %></td>
<% else %>
<td>No Overtime</td>
<% end %>
<td><%= link_to 'Show', meeting %></td>
<td><%= link_to 'Edit', edit_meeting_path(meeting) %></td>
<td><%= link_to 'Destroy', meeting, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br><br>
【问题讨论】:
标签: ruby-on-rails ruby datetime