ActiveRecord Strict Loading in Rails
When using ActiveRecord, lazy loading is the default behavior, where associated records are loaded when accessed. While convenient, this can lead to N+1 query problems, where an unanticipated number of database queries are triggered, potentially degrading performance.
Strict loading is a countermeasure to this issue. When enabled, it enforces the eager loading of associations, meaning all necessary data is loaded upfront in a single query. This approach mitigates the risk of N+1 queries and makes data fetching more efficient and predictable.
Strict loading can be set at various levels:
Globally: Set strict loading for all models by configuring it in the application:
config.active_record.strict_loading_by_default = true
Model Level: Enable strict loading for a specific model:
class Book < ApplicationRecord
has_many :chapters, strict_loading: true
end
Association Level: Apply it to specific associations:
has_many :comments, strict_loading: true
Query Level: Use it on a per-query basis:
User.strict_loading.find(params[:id])
Tweet