GAURAV VARMA
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
5endNow, 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::StrictLoadingViolationErrorFixing the error
Simply include the associations beforehand:
1article = Article.includes(:comments).strict_loading.first
2article.comments # works as expectedYou can verify strict loading is active:
1article.strict_loading? # => trueYou can also check if associated records respect strict loading:
1article.comments.all?(&:strict_loading?) # => trueEnabling strict loading per association
You can enforce strict loading on a specific association:
1class Article < ApplicationRecord
2 has_many :comments, strict_loading: true
3endNow, accessing comments without eager loading raises an error, even if the model itself isn't strict:
1article = Article.first
2article.comments # => Raises ActiveRecord::StrictLoadingViolationErrorEnabling strict loading on queries
If you want to enforce strict loading for specific queries only, use:
1Article.strict_loading.loadEnable globally
Strict loading can be enabled for all models via configuration:
1# config/application.rb
2config.active_record.strict_loading_by_default = trueThis 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 = :logThis 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: