ActiveRecord::Batches provides methods like find_each, find_in_batches,
and in_batches to process records in batches, reducing the load on the database and memory consumption.
By default, records are processed in ascending order by primary key(ID).
Before
Before Rails 7.1, using in_batches without a block on an ActiveRecord relation did not support descending order, even if it was specified. Instead, records were processed in ascending order.
Note that the ordering works fine for both find_each
and find_in_batches methods with ASC/DESC.
It also works fine when calling in_batches with a block.
User.in_batches(order: :desc) {}
(0.8ms) SELECT "users"."id" FROM "users" ORDER BY "users"."id" DESC LIMIT ? [["LIMIT", 1000]]But without a block it processes in ascending order.
User.in_batches(order: :desc).each {}
(0.4ms) SELECT "users"."id" FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1000]]After
Rails 7.1 supports descending order for in_batches without block.
Now in_batches method without a block works fine for both ASC/DESC order values.
User.in_batches(order: :desc).each {}
User Ids (2.7ms) SELECT "users"."id" FROM "users" ORDER BY "users"."id" DESC LIMIT $1 [["LIMIT", 1000]]