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
相关产品推荐
相关产品推荐

