订购批次清除解决方案

Ordered batches clear solution

在ruby/rails中给出以下代码,块代码被省略。

Model.order(id: :desc).find_in_batches { |group| ... }

如果你运行这个,你会收到警告。

Scoped order and limit are ignored, it's forced to be batch order and batch size

当然我们可以使用一些自定义样板代码来实现这一点,但我想知道是否有 rails-way?

我找到了 this,但我看不出有可能改变它的行为。如果我不需要 asc,但我需要 desc 怎么办。

直接来自 docs:

NOTE: It’s not possible to set the order. That is automatically set to ascending on the primary key (“id ASC”) to make the batch ordering work. This also means that this method only works when the primary key is orderable (e.g. an integer or string).

故意限制为 primary_key 顺序的原因是这些值不会改变。因此,如果您在遍历数据时改变数据,您就不会得到重复的选项。

id: :desc 的情况下,您将不会获得在获取初始批次的事务开始后插入的新记录。

参考资料

https://rails.lighthouseapp.com/projects/8994/tickets/2502-patch-arbase-reverse-find_in_batches

https://ww.telent.net/2012/5/4/changing_sort_order_with_activerecord_find_in_batches

ActiveRecord find_each combined with limit and order