---
title: "Rails 5.1 adds support for limit in batch processing"
description:
  "Rails 5.1 can now limit the number of records fetched for batch processing."
canonical_url: "https://www.bigbinary.com/blog/rails-5-1-adds-support-for-limit-in-batch-processing"
markdown_url: "https://www.bigbinary.com/blog/rails-5-1-adds-support-for-limit-in-batch-processing.md"
---

# Rails 5.1 adds support for limit in batch processing

Rails 5.1 can now limit the number of records fetched for batch processing.

- Author: Mohit Natoo
- Published: May 23, 2017
- Categories: Rails 5.1, Rails

Before Rails 5.1, we were not able to limit the number of records fetched in
batch processing.

Let's take an example. Assume our system has 20 users.

```ruby

 User.find_each{ |user| puts user.id }

```

The above code will print ids of all the 20 users.

There was no way to limit the number of records. Active Record's `limit` method
didn't work for batches.

```ruby

 User.limit(10).find_each{ |user| puts user.id }

```

The above code still prints ids of all 20 users, even though the intention was
to limit the records fetched to 10.

Rails 5.1
[has added support](https://github.com/rails/rails/commit/451437c6f57e66cc7586ec966e530493927098c7)
to limit the records in batch processing.

```ruby

 User.limit(10).find_each{ |user| puts user.id }

```

The above code will print only 10 ids in Rails 5.1.

We can make use of limit in `find_in_batches` and `in_batches` as well.

```ruby

 total_count = 0

 User.limit(10).find_in_batches(batch_size: 4) do |batch|
   total_count += batch.count
 end

 total_count
#=> 10

```

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-1-adds-support-for-limit-in-batch-processing)
