首页 > 解决方案 > 有效地从模型中批量删除条目

问题描述

假设我有一个模型书。我想删除在特定日期之前创建的所有条目和满足特定条件的书籍,没有 ISBN 的书籍。

获取 id 并批量运行删除作业是最有效的方法吗?注意:- 我知道 delete 比 destroy_all 快,但在这种情况下我不希望跳过回调。

例子

Books.select(:id).where(isbn: nil).find_in_batches(batch_size: 1000) do |ids|
  Books.where(id: ids).destroy_all
end

标签: ruby-on-railspostgresqlactiverecord

解决方案


destroy_all是相同的:

books.each(&:destroy)

正如您在源代码中看到的

所以你可以:

Books.select(:id).where(isbn: nil).find_in_batches(batch_size: 1000) do |books|
  # since destroy_all is only a ActiveRecord::Relation method
  books.each(&:destroy)
end

这是以最有效的方式执行此操作并触发回调的最小查询设置。

注意:如果您的回调需要任何其他属性而不是id加载,您应该将其添加到您的select查询中。


推荐阅读