Demystifying eager loading with ActiveRecord
Eager loading in ActiveRecord is a great feature. It prevents what's called the "n+1" problem. From the docs
Eager loading is a way to find objects of a certain class and a number of named associations. This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each need to display their author triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 2.
The docs then give this example:
This can scare beginners, as it did to me when I started learning about eager loading. This query doesn't magically work by itself. You must have the proper associations set up in your models. Once I started to think of that include clause in terms of the associations, everything made sense:
26 January 2010