---
title: "Forward ActiveRecord::Relation#count to Enumerable#count"
description:
  "Forward ActiveRecord::Relation#count to Enumerable#count if block given"
canonical_url: "https://www.bigbinary.com/blog/forwarding-active-record-relation-count-to-enumerable-count"
markdown_url: "https://www.bigbinary.com/blog/forwarding-active-record-relation-count-to-enumerable-count.md"
---

# Forward ActiveRecord::Relation#count to Enumerable#count

Forward ActiveRecord::Relation#count to Enumerable#count if block given

- Author: Rohit Arolkar
- Published: May 1, 2017
- Categories: Rails 5.1, Rails

Let's say that we want to know all the deliveries in progress for an order.

The following code would do the job.

```ruby

class Order
  has_many :deliveries

  def num_deliveries_in_progress
    deliveries.select { |delivery| delivery.in_progress? }.size
  end

end

```

But usage of `count` should make more sense over a `select`, right?

```ruby

class Order
  has_many :deliveries

  def num_deliveries_in_progress
    deliveries.count { |delivery| delivery.in_progress? }
  end

end

```

However the changed code would return count for all the order deliveries, rather
than returning only the ones in progress.

That's because `ActiveRecord::Relation#count` silently discards the block
argument.

Rails 5.1
[fixed this issue](https://github.com/rails/rails/pull/24203/files#diff-e0e70620d0897d6819a6bcc2b5ee7a73).

```ruby

module ActiveRecord
  module Calculations

    def count(column_name = nil)
      if block_given?
        to_a.count { |*block_args| yield(*block_args) }
      else
        calculate(:count, column_name)
      end
    end

  end
end

```

So now, we can pass a block to `count` method.

## Links

- [Human page](https://www.bigbinary.com/blog/forwarding-active-record-relation-count-to-enumerable-count)
