Skip to content

Commit 1a80133

Browse files
committed
Merge pull request rails#12748 from dm1try/fix_counter_cache_for_through_association
Fixes rails#11079, prevent the counter cache from being decremented twice when destroying a record on a has_many :through association
2 parents b31b6e6 + dbb7ee1 commit 1a80133

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
* Prevent the counter cache from being decremented twice when destroying
2+
a record on a has_many :through association.
3+
4+
Fixes #11079.
5+
6+
*Dmitry Dedov*
7+
18
* Unify boolean type casting for `MysqlAdapter` and `Mysql2Adapter`.
29
`type_cast` will return `1` for `true` and `0` for `false`.
310

activerecord/lib/active_record/associations/has_many_through_association.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def delete_records(records, method)
163163

164164
delete_through_records(records)
165165

166-
if source_reflection.options[:counter_cache]
166+
if source_reflection.options[:counter_cache] && method != :destroy
167167
counter = source_reflection.counter_cache_column
168168
klass.decrement_counter counter, records.map(&:id)
169169
end

activerecord/test/cases/associations/has_many_through_associations_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,15 @@ def test_update_counter_caches_on_replace_association
514514
assert_equal(post.taggings.count, post.taggings_count)
515515
end
516516

517+
def test_update_counter_caches_on_destroy
518+
post = posts(:welcome)
519+
tag = post.tags.create!(name: 'doomed')
520+
521+
assert_difference 'post.reload.taggings_count', -1 do
522+
tag.tagged_posts.destroy(post)
523+
end
524+
end
525+
517526
def test_replace_association
518527
assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)}
519528

0 commit comments

Comments
 (0)