rails find_each方法源码分析

在项目中我们经常会使用如下代码

1
2
3
Product.all.each do |product|
do_something
end

在实际应该中如果Product表太大,一次读取会把内存占满,Rails为了解决这个问题提供了两个方法,find_each和find_in_batches方法,把记录分成几个批次,因为find_each其实最终就是调用的find_in_batches,所以这里我们以find_in_batches为例。

1
2
3
Product.all.find_in_batches(start: 2000, batch_size: 5000,include: :infos) do |products|
do_something
end