Today I Learned

hashrocket A Hashrocket project

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])
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.