Rails按指定键统计Hash及按月分组时如何筛选2019年1月后数据
解决方案
推荐优先选择数据库层面过滤的方案,性能最优:
方案1:查询时直接过滤时间范围(推荐)
直接在ActiveRecord查询链中增加时间条件,从源头减少查询的数据量:
# 定义起始时间为2019年1月1日0点 start_time = Time.new(2019, 1, 1) Companion.where(companion_type: 1) .joins(:tasks) .where(tasks: {status: 3}) .where("created_at >= ?", start_time) .group_by_month(:created_at) .size
注意:如果
created_at字段同时存在于companions和tasks两张表中,需要明确指定表名避免歧义,比如把条件改成where("tasks.created_at >= ?", start_time)即可。
方案2:对已拿到的Hash结果进行过滤
如果你已经获取了全量的统计Hash,不想再发起数据库查询,可以直接用Ruby的Hash筛选方法处理:
# 原查询获取全量统计结果 full_stat = Companion.where(companion_type: 1).joins(:tasks).where(tasks: {status: 3}).group_by_month(:created_at).size # 筛选2019年1月及之后的结果 start_date = Date.new(2019, 1, 1) filtered_stat = full_stat.select { |month, _| month >= start_date }
内容的提问来源于stack exchange,提问作者Noah_J.C_Lee
相关产品推荐
相关产品推荐

