Rails 5 Warning when fetching with Active Record

Abhishek Jain

By Abhishek Jain

on April 13, 2016

This blog is part of our  Rails 5 series.

With large data set we can run into memory issue. Here is an example.

1
2>> Post.published.count
3=> 25000
4
5>> Post.where(published: true).each do |post|
6     post.archive!
7   end
8
9# Loads 25000 posts in memory
10

Rails 5 adds warning when loading large data set

To mitigate issue shown above Rails 5 has added config.active_record.warn_on_records_fetched_greater_than.

When this configuration is set to an integer value, any query that returns the number of records greater than the set limit, logs a warning.

1
2config.active_record.warn_on_records_fetched_greater_than = 1500
3
4>> Post.where(published: true).each do |post|
5     post.archive!
6   end
7
8=> Query fetched 25000 Post records: SELECT "posts".* FROM "posts" WHERE "posts"."published" = ? [["published", true]]
9   [#<Post id: 1, title: 'Rails', user_id: 1, created_at: "2016-02-11 11:32:32", updated_at: "2016-02-11 11:32:32", published: true>, #<Post id: 2, title: 'Ruby', user_id: 2, created_at: "2016-02-11 11:36:05", updated_at: "2016-02-11 11:36:05", published: true>,....]
10

This helps us find areas where potential problems exist and then we can replace inefficient queries with better ones.

1
2config.active_record.warn_on_records_fetched_greater_than = 1500
3
4>> Post.where(published: true).find_each do |post|
5     post.archive!
6   end
7
8# No warning is logged

If you liked this blog, you might also like the other blogs we have written. Check out the full archive.

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

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