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.
This commit is contained in:
Petrik 2023-09-20 13:23:48 +02:00
parent 0723e6c658
commit 677fa58873
2 changed files with 33 additions and 5 deletions

@ -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
# => #<ActiveRecord::Associations::CollectionProxy>
# user.address.city # => "Tatooine"
# user.comments.to_a # => [#<Comment:0x00...]
#
# user.strict_loading!(mode: :n_plus_one_only)
# user.address.city # => "Tatooine"
# user.comments
# user.comments.to_a # => [#<Comment:0x00...]
# user.comments.first.ratings.to_a
# => ActiveRecord::StrictLoadingViolationError
def strict_loading!(value = true, mode: :all)
unless [:all, :n_plus_one_only].include?(mode)

@ -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 # => [#<Comment:0x00...]
user.comments.first.likes.to_a # raises an ActiveRecord::StrictLoadingViolationError
```
[`strict_loading!`]: https://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-strict_loading-21
Scopes
------