Since rails 6.1rc has been released, we have summarized the new strict_loading features.
See: https://weblog.rubyonrails.org/releases/
#strict_loadingBy marking an object, the exception ActiveRecord :: StrictLoadingViolationError will be thrown when the object is loaded with an association delay.
$ dev = Developer.strict_loading.first
$ dev.audit_logs.to_a
=> ActiveRecord::StrictLoadingViolationError: Developer is marked as strict_loading and AuditLog cannot be lazily loaded.
See: https://github.com/rails/rails/pull/37400
ActiveRecord :: StrictLoadingViolationError is thrown when lazy loading is performed on all specified associations.class Developer < ApplicationRecord
has_many :projects, strict_loading: true
end
dev = Developer.first
dev.projects.first
# => ActiveRecord::StrictLoadingViolationError: The projects association is marked as strict_loading and cannot be lazily loaded.
See: https://github.com/rails/rails/pull/38541
ActiveRecord :: StrictLoadingViolationError when lazy loading.class Developer < ApplicationRecord
self.strict_loading_by_default = true
has_many :projects
end
dev = Developer.first
dev.projects.first
# => ActiveRecord::StrictLoadingViolationError Exception: Developer is marked as strict_loading and Project cannot be lazily loaded.
See: https://github.com/rails/rails/pull/39491
config.active_record.action_on_strict_loading_violationenables raising or logging an exception if strict_loading is set on an association. The default value is:raisein all environments. It can be changed to:logto send violations to the logger instead of raising.
config.active_record.action_on_strict_loading_violation = :log
See https://github.com/rails/rails/pull/40511 https://edgeguides.rubyonrails.org/configuring.html#configuring-active-record
This makes it possible to raise an exception in the development and test environments and keep the log output in the production environment.
The community is also actively discussing ways to prevent N + 1 from occurring. https://discuss.rubyonrails.org/t/n-1-queries-should-be-the-exception-not-the-easy-trap-to-fall-in/74537/14
Recommended Posts