From 8c6a19f639c59d478c48ccf8f70eb8e1f5f14170 Mon Sep 17 00:00:00 2001 From: Adrianna Chang Date: Wed, 22 Oct 2025 15:03:28 -0400 Subject: [PATCH] Patch run_callbacks instead of _run_commit_callbacks Ref: https://github.com/rails/rails/pull/55736/commits/207a254cedef2c381c2898bac960b91ce14ab3a7 _run_commit_callbacks is now a no-op; Rails aliases it to a `run_commit_callbacks!` implementation. We could patch the `!` version, but it can lead to issues depending on when callbacks are defined and when the `IdentityCache` module is included. Overriding `run_callbacks` is a more robust solution. --- CHANGELOG.md | 2 ++ lib/identity_cache/query_api.rb | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b3a3ec5..26a1a908 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Patch `run_callbacks` instead of `_run_commit_callbacks` to expire cache prior to `after_commit` callbacks. (#602) + ## 1.6.3 - Split the `with_deferred_parent_expiration` and `with_deferred_parent_expiration`. (#578) diff --git a/lib/identity_cache/query_api.rb b/lib/identity_cache/query_api.rb index d37b2448..a90171b2 100644 --- a/lib/identity_cache/query_api.rb +++ b/lib/identity_cache/query_api.rb @@ -165,11 +165,20 @@ def cache_fetch_includes # cache reads that happen from the ordering of callbacks. For example, if an after_commit # callback enqueues a background job, then we don't want it to be possible for the # background job to run and load data from the cache before it is invalidated. - def _run_commit_callbacks - if destroyed? || transaction_changed_attributes.present? - expire_cache + if ActiveRecord.version >= Gem::Version.new("7.1") + def run_callbacks(kind, type = nil) + if kind == :commit && (destroyed? || transaction_changed_attributes.present?) + expire_cache + end + super + end + else + def run_callbacks(kind) + if kind == :commit && (destroyed? || transaction_changed_attributes.present?) + expire_cache + end + super end - super end # Invalidate the cache data associated with the record. Returns `true` on success,