Picture of the author

GAURAV VARMA

← BACK TO BLOG

Rails 6.1 introduces Strict Loading to catch N+1 queries


Rails 6.1 introduces strict loading, a helpful feature that enforces eager loading to prevent accidental N+1 queries.

What is strict loading?

Strict loading raises an ActiveRecord::StrictLoadingViolationError if an association is accessed without being eager-loaded. It’s a great tool to catch inefficient queries early in development or test environments.

Enabling strict loading per model

You can set strict loading as the default behavior for all records of a model:

1class Article < ApplicationRecord
2  self.strict_loading_by_default = true
3
4  has_many :comments
5end

Now, if you fetch an Article and try to access its comments without including them, Rails will raise an error:

1article = Article.strict_loading.first
2article.comments # => Raises ActiveRecord::StrictLoadingViolationError

Fixing the error

Simply include the associations beforehand:

1article = Article.includes(:comments).strict_loading.first
2article.comments # works as expected

You can verify strict loading is active:

1article.strict_loading? # => true

You can also check if associated records respect strict loading:

1article.comments.all?(&:strict_loading?) # => true

Enabling strict loading per association

You can enforce strict loading on a specific association:

1class Article < ApplicationRecord
2  has_many :comments, strict_loading: true
3end

Now, accessing comments without eager loading raises an error, even if the model itself isn't strict:

1article = Article.first
2article.comments # => Raises ActiveRecord::StrictLoadingViolationError

Enabling strict loading on queries

If you want to enforce strict loading for specific queries only, use:

1Article.strict_loading.load

Enable globally

Strict loading can be enabled for all models via configuration:

1# config/application.rb
2config.active_record.strict_loading_by_default = true

This ensures all models and their associations are protected from lazy loading.

Logging violations instead of raising

In production, instead of raising an error, you can choose to just log violations:

1# config/environments/production.rb
2config.active_record.action_on_strict_loading_violation = :log

This helps teams gradually adopt strict loading without immediately breaking the app.

Summary

Strict loading in Rails 6.1 is a powerful ally against N+1 query issues. By enforcing eager loading and surfacing violations early, it improves app performance and encourages better data access patterns.

For more, check out: