Skip to content

Commit 7fd8079

Browse files
authored
Merge pull request rails#41789 from kamipo/update_cache_key_after_mutation
Clear `@cache_keys` cache after `update_all`, `delete_all`, `destroy_all`
2 parents fe8f47b + 5b10aca commit 7fd8079

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

activerecord/lib/active_record/relation.rb

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@ def update_all(updates)
488488
stmt = arel.compile_update(values, table[primary_key])
489489
stmt.table(source)
490490

491-
klass.connection.update(stmt, "#{klass} Update All")
491+
klass.connection.update(stmt, "#{klass} Update All").tap { reset }
492492
end
493493

494494
def update(id = :all, attributes) # :nodoc:
@@ -616,10 +616,7 @@ def delete_all
616616
stmt = arel.compile_delete(table[primary_key])
617617
stmt.from(source)
618618

619-
affected = klass.connection.delete(stmt, "#{klass} Destroy")
620-
621-
reset
622-
affected
619+
klass.connection.delete(stmt, "#{klass} Destroy").tap { reset }
623620
end
624621

625622
# Finds and destroys all records matching the specified conditions.
@@ -701,6 +698,7 @@ def reset
701698
@delegate_to_klass = false
702699
@to_sql = @arel = @loaded = @should_eager_load = nil
703700
@offsets = @take = nil
701+
@cache_keys = nil
704702
@records = nil
705703
self
706704
end

activerecord/test/cases/collection_cache_key_test.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
require "models/topic"
88
require "models/post"
99
require "models/comment"
10+
require "models/ship"
1011

1112
module ActiveRecord
1213
class CollectionCacheKeyTest < ActiveRecord::TestCase
@@ -101,6 +102,33 @@ class CollectionCacheKeyTest < ActiveRecord::TestCase
101102
assert_match(/\Acomments\/query-(\h+)-(\d+)-(\d+)\z/, comments.cache_key)
102103
end
103104

105+
test "update_all will update cache_key" do
106+
developers = Developer.where(name: "David")
107+
cache_key = developers.cache_key
108+
109+
developers.update_all(updated_at: Time.now.utc)
110+
111+
assert_not_equal cache_key, developers.cache_key
112+
end
113+
114+
test "delete_all will update cache_key" do
115+
developers = Developer.where(name: "David")
116+
cache_key = developers.cache_key
117+
118+
developers.delete_all
119+
120+
assert_not_equal cache_key, developers.cache_key
121+
end
122+
123+
test "destroy_all will update cache_key" do
124+
developers = Developer.where(name: "David")
125+
cache_key = developers.cache_key
126+
127+
developers.destroy_all
128+
129+
assert_not_equal cache_key, developers.cache_key
130+
end
131+
104132
test "it triggers at most one query" do
105133
developers = Developer.where(name: "David")
106134

0 commit comments

Comments
 (0)