The N+1 Queries issue
NoBrainer allows eager loading of associations with
eager_load() to avoid the N+1
queries issue. Suppose we have posts and comments:
Suppose that we want to display the list of the most recent comments along with their post and author. The following will trigger 201 database queries:
Using eager_load() in a query
We can use
eager_load to eager load the models to reduce the number of queries to 3:
eager_load() accepts arrays and hashes to describe the associations to eager load.
NoBrainer allows criteria to be specified on how to include these associations. When specifying criteria, nested eager_load can be used to further load associations. For example:
Remember that NoBrainer will use the model default scopes on all associations,
except on the
in queries such as
Model.where(foreign_key.in => [ids]) to retrieve
associations and can leverage secondary indexes.
You may add an
:index => true option on the
belongs_to association to improve
read performance (at the cost of write performance).
NoBrainer prefers such queries because RethinkDB outer joins cannot be used with an index, and also joins often retrieve too much data when instances are shared across associations.
Using eager_load on an array
NoBrainer allows to eager loading associations on a given array of model
NoBrainer.eager_load(). The first argument is the array of
model instances, and the second argument is the same as the criteria argument.