From 677fa5887354505f756b840b281bf9ff17d868d4 Mon Sep 17 00:00:00 2001 From: Petrik Date: Wed, 20 Sep 2023 13:23:48 +0200 Subject: [PATCH] Improve `strict_loading` documentation [ci-skip] Expand examples by adding singular associations. Expand the guides with `strict_loading!`. Also add `to_a` to code examples as loading the associations is required to raise the errors. --- activerecord/lib/active_record/core.rb | 11 ++++++---- guides/source/active_record_querying.md | 27 ++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 3000cadfe0..b41feb172d 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -615,7 +615,9 @@ def strict_loading? # # user = User.first # user.strict_loading! # => true - # user.comments + # user.address.city + # => ActiveRecord::StrictLoadingViolationError + # user.comments.to_a # => ActiveRecord::StrictLoadingViolationError # # ==== Parameters @@ -629,12 +631,13 @@ def strict_loading? # # user = User.first # user.strict_loading!(false) # => false - # user.comments - # => # + # user.address.city # => "Tatooine" + # user.comments.to_a # => [# "Tatooine" - # user.comments + # user.comments.to_a # => [# ActiveRecord::StrictLoadingViolationError def strict_loading!(value = true, mode: :all) unless [:all, :n_plus_one_only].include?(mode) diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 4b1bdd59c0..e53c3d456e 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -1754,15 +1754,40 @@ some associations. To make sure no associations are lazy loaded you can enable By enabling strict loading mode on a relation, an `ActiveRecord::StrictLoadingViolationError` will be raised if the record tries -to lazily load an association: +to lazily load any association: ```ruby user = User.strict_loading.first +user.address.city # raises an ActiveRecord::StrictLoadingViolationError user.comments.to_a # raises an ActiveRecord::StrictLoadingViolationError ``` [`strict_loading`]: https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-strict_loading +### `strict_loading!` + +We can also enable strict loading on the record itself by calling [`strict_loading!`][]: + +```ruby +user = User.first +user.strict_loading! +user.address.city # raises an ActiveRecord::StrictLoadingViolationError +user.comments.to_a # raises an ActiveRecord::StrictLoadingViolationError +``` + +`strict_loading!` also takes a `:mode` argument. Setting it to `:n_plus_one_only` +will only raise an error if an association that will lead to an N + 1 query is +lazily loaded: + +```ruby +user.strict_loading!(mode: :n_plus_one_only) +user.address.city # => "Tatooine" +user.comments.to_a # => [#