Recently, I published an article about “Stop using manual preloading in your Rails application; use this instead.” Many people were interested, bu

Automatic preloading in Rails: the dream that came true.

submited by
Style Pass
2023-03-14 15:30:09

Recently, I published an article about “Stop using manual preloading in your Rails application; use this instead.” Many people were interested, but I failed to explain the ultimate solution. Considering that I still see posts about ActiveRecord includes, I want to elaborate on the idea deeply.

Most often, in the Ruby on Rails world, it’s all about database queries so we will stop on that part. Ruby on Rails offers a built-in solution for dealing with N+1 issues regarding fetching associations.

The problem is that for every user, there will be a query to a database to fetch accounts; moreover, for every account then, there will be a query to fetch its contacts.

Rails’ solution is to use includes at the very beginning of the chain. The fixed code would look like this:

If you have ever worked with includes before, please pause here and remember what you didn’t like about it.

Leave a Comment