From 17bf62033edd4f0934c9f4a9e0c7a5f0f765975b Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Sun, 27 May 2018 12:06:58 +0900 Subject: Fix that association's after_touch is not called with counter cache Since #31405, using `#increment!` with touch option instead of `#touch` to touch belongs_to association if counter cache is enabled. It caused the regression since `#increment!` won't invoke after_touch callbacks even if touch option is given. To fix the regression, make `#increment!` invokes after_touch callbacks if touch option is given. Fixes #31559. Fixes #32408. --- activerecord/lib/active_record/callbacks.rb | 4 ++++ .../cases/associations/belongs_to_associations_test.rb | 17 +++++++++++++++++ activerecord/test/models/topic.rb | 10 ++++++++++ 3 files changed, 31 insertions(+) diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index fd6819d08f..0a29c5134e 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -318,6 +318,10 @@ module ActiveRecord _run_touch_callbacks { super } end + def increment!(*, touch: nil) # :nodoc: + touch ? _run_touch_callbacks { super } : super + end + private def create_or_update(*) diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 9ca9ab62a1..0cc4ed7127 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -557,6 +557,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal 1, Topic.find(topic.id)[:replies_count] end + def test_belongs_to_counter_after_touch + topic = Topic.create!(title: "topic") + + assert_equal 0, topic.replies_count + assert_equal 0, topic.after_touch_called + + reply = Reply.create!(title: "blah!", content: "world around!", topic_with_primary_key: topic) + + assert_equal 1, topic.replies_count + assert_equal 1, topic.after_touch_called + + reply.destroy! + + assert_equal 0, topic.replies_count + assert_equal 2, topic.after_touch_called + end + def test_belongs_to_touch_with_reassigning debate = Topic.create!(title: "debate") debate2 = Topic.create!(title: "debate2") diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index 2e386d7669..72699046f9 100644 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -81,6 +81,16 @@ class Topic < ActiveRecord::Base self.class.after_initialize_called = true end + attr_accessor :after_touch_called + + after_initialize do + self.after_touch_called = 0 + end + + after_touch do + self.after_touch_called += 1 + end + def approved=(val) @custom_approved = val write_attribute(:approved, val) -- cgit v1.2.3