Counting Records With ActiveRecord

While counting records with ActiveRecord seems straightforward, you can quickly experience performance problems if not done properly. In the context of Rails ActiveRecord, the methods for counting records each do it a bit differently. Let's take a look at the three methods available in Rails:

  1. count - When called on an ActiveRecord::Relation object, count will perform a SQL COUNT query, which is very fast, especially on large result sets.

  2. size - Like count, size works differently depending on whether you call it on an array or an ActiveRecord::Relation object. When called on an array, size is identical to length: it returns the number of objects in the array. But things get interesting when you call size on an ActiveRecord::Relation. In this case, it behaves differently depending on whether or not the relation’s records have been loaded from the database yet.

  3. length - This is a plain Ruby method that functions like count when called on an array. The difference is that ActiveRecord does not define its own length method. So if you call length on an ActiveRecord::Relation object, it will be converted to an array and will count the array’s objects.

So here are some tips:
1. Use count if you need to just count records in the controller or model.
2. Use size if you want to count records in the view or if you are not sure if they were loaded in the memory.
3. Don’t use length on ActiveRecord’s collection, this is meant to be used on an Array.

Go Back To Blog.