Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

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/

Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.