From ea2226605ad5708ce8d9c3e2631054ef5990ce2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Hasi=C5=84ski?= Date: Fri, 21 Jan 2022 22:21:35 +0100 Subject: [PATCH] Add a note in guide for a counter cache caveat Counter cache can hold stale value if user changes primary key's value. This caveat is not mentioned in guides, but according to #16159 comments it should be. --- guides/source/association_basics.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 01e569dd89..551b7e7515 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -1037,7 +1037,15 @@ end NOTE: You only need to specify the `:counter_cache` option on the `belongs_to` side of the association. -Counter cache columns are added to the containing model's list of read-only attributes through `attr_readonly`. +Counter cache columns are added to the owner model's list of read-only +attributes through `attr_readonly`. + +If for some reason you change the value of an owner model's primary key, and do +not also update the foreign keys of the counted models, then the counter cache +may have stale data. In other words, any orphaned models will still count +towards the counter. To fix a stale counter cache, use [`reset_counters`][]. + +[`reset_counters`]: https://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-reset_counters ##### `:dependent`