Rails 6.1 introduced a powerful feature called “strict loading” that helps prevent N+1 queries by raising an error when you try to load an association that hasn’t been preloaded:
# Enable strict loading globally in config/application.rb
config.active_record.strict_loading_by_default = true
# Or enable it on specific models
class User < ApplicationRecord
self.strict_loading_by_default = true
end
# Or enable it for specific instances
user = User.first
user.strict_loading!
# Now this will raise an error if comments aren't preloaded
user.comments.each { |comment| puts comment.body }
# => ActiveRecord::StrictLoadingViolationError:
# The comments association is being loaded without being preloaded.
This feature is extremely useful during development to catch potential performance issues before they reach production.