ActiveRecord::Batches
provides public methods like find_each, find_in_batches and in_batches
to work with the records in batches
which helps in reducing memory consumption.
Before Rails 6.1, the order was automatically set on the primary key,
which always returns results in ascending order.
In many cases, we might need to process newer records before older records.
This wasn’t possible even if provided the order manually on the scope used for batching,
as order gets overridden by find_each, etc.
With Rails 6.1
Rails 6.1 now supportsorder option for find_each, find_in_batches and in_batches methods.
find_each
Let’s take a look how this works now for find_each.
find_in_batches
Similarly for find_in_batches-
in_batches
And support for in_batches-
As shown in the above example,
in_batches with order: :desc queries the user table with
descending order clause which returns the batches in descending order.
Note that in_batches, just yields a relation.
By default the relation has no ordering,
so the records within batches are processed in ascending order which
is the default order on User ActiveRecord::Relation.
We can make this behave like other scenarios above
by providing an order to intermediate relation object-