Maintenant que rails 6.1rc est sorti, nous avons mis au point une nouvelle fonctionnalité, la fonction strict_loading
.
See: https://weblog.rubyonrails.org/releases/
#strict_loading
En marquant un objet, l'exception ActiveRecord :: StrictLoadingViolationError
sera déclenchée lorsque l'objet est chargé avec un délai d'association.
$ 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
lors du chargement différé.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
lors du chargement différé.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_violation
enables raising or logging an exception if strict_loading is set on an association. The default value is:raise
in all environments. It can be changed to:log
to 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
Cela permet de lever une exception dans les environnements de développement et de test et de conserver la sortie du journal dans l'environnement de production.
La communauté discute également activement des moyens d'empêcher l'apparition de N + 1. https://discuss.rubyonrails.org/t/n-1-queries-should-be-the-exception-not-the-easy-trap-to-fall-in/74537/14