Active Record's includes method
includes is a method in Rails provided by the ActiveRecord that is used to preload the records limiting the count of the SQL queries to the database. This technique of query is also known as eager loading where related child objects are loaded automatically with it’s parent. For e.g
1 2 3 4 5 6 7 8 class CategoriesController < ApplicationController def show @category = Category.includes(:articles).limit(5) end end
The above code will fetch the five categories and it’s associated all the articles at once without having to ping the database multiple times.
How It Works
Assume the above models Category and Article have
relationship. Setting up the association allows those class to inherit methods
from the ActiveRecord::Associations module. One of which is association method
which takes a name as an argument(in our case is ‘:articles’). This method will
try to fetch the requested association data out of the @association _ cache(generally empty hash)
instance variable by assuming as it’s already been loaded into memory. If the
association data is not in the @association _ cache, then the association will
have to be loaded from which ActiveRecord fetch the data. For e.g
Hence, Rails pre-populated the hash with the respective Category’s articles.
In this way, ‘includes’ method preload the @association_cache instance variable, and, when Active Record goes to fetch the data, it is already there and doesn’t have to query the database again.