我们常常需要遍历大量记录,例如向大量用户发送实时通讯、导出数据等。

Rails 提供了两种方法来解决这个问题,两种方法都是把整个记录分成多个对内存友好的批处理。

  1. 第一种方法是通过 find_each 方法每次检索一批记录,然后逐一把每条记录作为模型传入块。
  2. 第二种方法是通过 find_in_batches 方法每次检索一批记录,然后把这批记录整个作为模型数组传入块。

find_each  find_in_batches 能处理模型,也能处理关系:

Order.pending.find_each(start: 2000) do |user|
  # do something
end
  • Sorting ASC on the PK is used to make the batch ordering work.
  • Limit is used to control the batch sizes.

但是关系不能有顺序,因为这个方法在迭代时有既定的顺序。

如果想在批量操作里加上排序,这或许是一种方法:

batch_size = 500
ids = User.order('created_at DESC').pluck(:id)
ids.each_slice(batch_size) do |user_ids|
  users = User.where(id: user_ids).order('created_at DESC')
  # do something
end
4条评论 顺序楼层
请先登录再回复