Batch Active Record Operations with `find_each`
Iterating over a collection of ActiveRecord models can incur a performance hit to your application, especially when the result set is large.
A basic query like all
or where
could return tens of thousand of records. When that query returns, it will instantiate your records all at once, loading them into memory, and potentially leading to instability. Luckily if we need to operate on a large result set, we can use the find_each
method to work in batches on our query.
find_each
works by using the find_in_batches
method under the hood, with a default batch size of 1000
.
# This is bad ❌
Customer.where(active: true).each do |customer|
# ....
end
# This is good ☑️
Customer.where(active: true).find_each do |customer|
# ....
end
If you need to, you can also adjust the batch size by passing the batch_size
kwarg to find_each
Customer.where(active: true).find_each(batch_size: 2000) do |customer|
# ...
end
https://devdocs.io/rails~6.1/activerecord/batches#method-i-find_each
H/T https://rails.rubystyle.guide/
Tweet