Rails 5.1 doesn't load all records on calling Model.all#inspect

Mohit Natoo

Mohit Natoo

November 14, 2017

This blog is part of our  Rails 5.1 series.

Let's take a project with hundreds of users. When we call inspect on User.all, we see an array of 10 users followed by .... That means the output of #inspect method shows data only for 10 records.

> User.all.inspect
User Load (3.7ms)  SELECT  "users".* FROM "users"
=> "#<ActiveRecord::Relation [
#<User id: 1, email: \"[email protected]\" >,
#<User id: 2, email: \"[email protected]\">,
#<User id: 3, email: \"[email protected]\">,
#<User id: 4, email: \"[email protected]\">,
#<User id: 5, email: \"[email protected]\">,
#<User id: 6, email: \"[email protected]\">,
#<User id: 7, email: \"[email protected]\">,
#<User id: 8, email: \"[email protected]\">,
#<User id: 9, email: \"[email protected]\">,
#<User id: 10, email:\"[email protected]\">,
...]>"

We can see that the query executed in the process is fetching all the records even though the output doesn't need all of them.

In Rails 5.1, only the needed records are loaded when inspect is called on ActiveRecord::Relation.

> User.all.inspect
User Load (3.7ms)  SELECT  "users".* FROM "users" LIMIT $1 /*application:Ace Invoice*/  [["LIMIT", 11]]

=> "#<ActiveRecord::Relation [
#<User id: 1, email: \"[email protected]\" >,
#<User id: 2, email: \"[email protected]\">,
#<User id: 3, email: \"[email protected]\">,
#<User id: 4, email: \"[email protected]\">,
#<User id: 5, email: \"[email protected]\">,
#<User id: 6, email: \"[email protected]\">,
#<User id: 7, email: \"[email protected]\">,
#<User id: 8, email: \"[email protected]\">,
#<User id: 9, email: \"[email protected]\">,
#<User id: 10, email:\"[email protected]\">,
...]>"

We can see in the above case that query executed has limit constraint and hence only the required number of records are loaded.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.