You need to enable JavaScript to run this app. Ruby on Rails如何实现每日总时长仅显示一次不重复出现
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails如何实现每日总时长仅显示一次不重复出现

解决方案

步骤1:修改视图层代码(index.html.erb)

将总时长的展示逻辑从单条会议的循环中移出,放在当日所有会议列表的末尾,每天仅计算渲染一次即可:

<%= month_calendar events: @meetings do |date, meetings| %>
  <%= date %>
  <% meetings.each do |meeting| %>
    <div class="primary">
      <button type="button" class="btn btn-success"> <%= Time.at(meeting.start_time).utc.strftime("%I:%M %P") %></button>
      <button type="button" class="btn btn-danger"> <%= Time.at(meeting.end_time).utc.strftime("%I:%M %P") %></button>
    </div>
  <% end %>
  <!-- 仅当日有会议时展示总时长,每天仅显示一次 -->
  <% if meetings.any? %>
    <button type="button" class="btn btn-warning" >
      <%= Time.at(Meeting.daily_total_duration(date)).utc.strftime("%H hrs & %M mins ") %>
    </button>
  <% end %>
<% end %>

步骤2:优化模型层计算逻辑

把原来的实例方法改为类方法,直接根据传入的日期查询当日总时长,避免重复查询,性能更优:

class Meeting < ApplicationRecord
  before_save :set_duration

  def set_duration
    self.duration = (end_time - start_time).to_i
  end

  # 类方法,传入指定日期直接计算当日所有会议累计时长
  def self.daily_total_duration(date)
    Meeting.where("start_time >= ? AND end_time < ?", date.beginning_of_day, date.end_of_day).sum(:duration)
  end
end

逻辑说明

原问题核心是总时长按钮被写在了meetings.each循环内部,当天有多少条会议记录,总时长就会重复显示多少次。修改后总时长渲染逻辑放在循环外,每个日期块仅执行一次计算和渲染,自然不会重复展示。

内容的提问来源于stack exchange,提问作者Sarah Duffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:18:03