> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/load-records-in-batches-with-find-each.md).

# Load Records In Batches With find\_each

The base enumerable method offered by Ruby is `#each`. If you need to interact with an array of elements, that's a method you'll reach for at some point.

When working with an `ActiveRecord` collection in Rails, you should use the [`#find_each`](https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/Batches.html#method-i-find_each) method instead of `#each`. That's because under the hood it batches the records that it will load in 1000 at a time. This is important to keep your server's resource usage from exploding when requesting a ton of records.

Consider a `users` table that contains 10,000 records that are *active*.

```ruby
User.where(active: true).each do |user|
  # do something
end
```

With `#each`, all 10,000 records will be loaded into memory at once as `ActiveRecord` objects. That's potentially a lot of load on the server's available memory. Then imagine the table contains 100,000 or 1,000,000 records. This can become a big problem.

```ruby
User.where(active: true).find_each do |user|
  # do something
end
```

With `#find_each`, which uses [`#find_in_batches`](https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/Batches.html#method-i-find_in_batches) under the hood, only 1000 `ActiveRecord` objects get loaded into memory at a time.

If you want to exercise more control over the batching, you can use `#find_in_batches` directly.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/load-records-in-batches-with-find-each.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
