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

Rails中用find_each替代where.not查询的实现方法

在Rails中用find_each实现带否定条件的分批查询

你不需要在find_each里直接加否定操作符——find_each只是ActiveRecord提供的分批加载数据的执行方法,只要先构建好带where.not的查询集合,再调用find_each就行。

你的原查询:

Task.where.not(client_ids: nil, client_ids: []).all

改成find_each的写法很简单,直接把.all换成.find_each并加上处理逻辑的块即可:

Task.where.not(client_ids: nil, client_ids: []).find_each do |task|
  # 在这里写你要处理单个task的逻辑,比如更新、导出等
end

补充说明

  • .all可以直接去掉,因为where.not返回的已经是ActiveRecord::Relation对象,调用find_each会自动执行查询并分批加载数据
  • 如果需要调整批次大小(默认是1000条),可以给find_each传参数,比如:
    Task.where.not(client_ids: nil, client_ids: []).find_each(batch_size: 500) do |task|
      # 处理逻辑
    end
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:07:01