Allow resetting singular associations #46165
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
has_one :author
andbelongs_to :author
each define areload_author
method on the owning model.reload_author
clears the cachedauthor
associate-object and eagerly fetches a new one from the database.In some cases, you know the cached associate is stale but not whether it will be needed again. If it isn’t, the database query from calling
reload_*
is wasted.Consider the following models:
At the 📍 in
Trial#deactivate
, we know we’ve potentially madeaccount
’sactive_trial
association stale. We don’t know ifaccount
will need to reference itsactive_trial
again. It would be useful to be able to evict the cachedactive_trial
, if any, and defer the database query until the next access.For collection associations,
ActiveRecord::Associations::CollectionProxy
provides a#reset
method in addition to#reload
. There’s not an equivalent way to reset a singular association, though. This PR adds one.