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

Mohit Natoo

By Mohit Natoo

on 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.

1> User.all.inspect
2User Load (3.7ms)  SELECT  "users".* FROM "users"
3=> "#<ActiveRecord::Relation [
4#<User id: 1, email: \"dirbee@example.com\" >,
5#<User id: 2, email: \"tee@example.com\">,
6#<User id: 3, email: \"scott@example.com\">,
7#<User id: 4, email: \"mark@example.com\">,
8#<User id: 5, email: \"ben@example.com\">,
9#<User id: 6, email: \"tina@example.com\">,
10#<User id: 7, email: \"tyler@example.com\">,
11#<User id: 8, email: \"peter@example.com\">,
12#<User id: 9, email: \"rutul@example.com\">,
13#<User id: 10, email:\"michael@example.com\">,

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.

1> User.all.inspect
2User Load (3.7ms)  SELECT  "users".* FROM "users" LIMIT $1 /*application:Ace Invoice*/  [["LIMIT", 11]]
4=> "#<ActiveRecord::Relation [
5#<User id: 1, email: \"dirbee@example.com\" >,
6#<User id: 2, email: \"tee@example.com\">,
7#<User id: 3, email: \"scott@example.com\">,
8#<User id: 4, email: \"mark@example.com\">,
9#<User id: 5, email: \"ben@example.com\">,
10#<User id: 6, email: \"tina@example.com\">,
11#<User id: 7, email: \"tyler@example.com\">,
12#<User id: 8, email: \"peter@example.com\">,
13#<User id: 9, email: \"rutul@example.com\">,
14#<User id: 10, email:\"michael@example.com\">,

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

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.