You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails where方法优化:created_at为nil时跳过该查询条件

Rails查询优化:移除不必要的时间范围查询

原方法中当created_at参数为nil时,会额外查询Transfer表的首尾记录生成时间范围,我们可以通过动态构建查询条件的方式,直接跳过created_at的条件判断,避免多余查询:

def transfers(material, capacity, category, created_at)
  # 抽离公共查询条件,减少代码冗余
  common_conditions = {
    status: %i[dispatched released returned],
    capacity: capacity
  }

  # 分别初始化发送方、接收方的基础查询
  sender_query = Transfer.where(common_conditions).where(sender_dispensary_id: id, material: material)
  receiver_query = Transfer.where(common_conditions).where(receiver_dispensary_id: id, material_id: material)

  # 仅当created_at不为空时,添加时间范围过滤
  unless created_at.nil?
    time_range = Time.given_month_range(created_at)
    sender_query = sender_query.where(created_at: time_range)
    receiver_query = receiver_query.where(created_at: time_range)
  end

  # 合并两个查询分支
  sender_query.or(receiver_query)
end

优化说明

  • 把重复的status、capacity条件抽成公共哈希,避免代码重复
  • 拆分发送方和接收方的查询逻辑,仅在created_at存在时才追加时间范围条件,当created_at为nil时,查询语句中完全不会包含created_at的过滤条件,和“从未添加该条件”的效果一致
  • 避免了原代码中Transfer.first和Transfer.last的额外查询,提升了性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:05:28