Skip to content

A platform for community discussion. Free, open, simple.

FIX: Liking whispers should not contribute to `Topic#like_count`. (#15703)

Alan Guo Xiang Tan4aa9a813ec16
diff --git a/app/models/post_action.rb b/app/models/post_action.rb
index a26998aa7c9..5bb7b39eb52 100644
--- a/app/models/post_action.rb
+++ b/app/models/post_action.rb
@@ -239,8 +239,7 @@ class PostAction < ActiveRecord::Base
end
if column == "like_count"
- topic_count = Post.where(topic_id: topic_id).sum(column)
- Topic.where(id: topic_id).update_all ["#{column} = ?", topic_count]
+ Topic.find_by(id: topic_id)&.update_action_counts
end
end
diff --git a/db/migrate/20220125052845_fix_topic_like_count_including_whispers.rb b/db/migrate/20220125052845_fix_topic_like_count_including_whispers.rb
new file mode 100644
index 00000000000..d296e846281
--- /dev/null
+++ b/db/migrate/20220125052845_fix_topic_like_count_including_whispers.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+class FixTopicLikeCountIncludingWhispers < ActiveRecord::Migration[6.0]
+ def up
+ whisper_post_type = 4
+
+ DB.exec(<<~SQL)
+ UPDATE topics SET like_count = tbl.like_count
+ FROM (
+ SELECT topic_id, SUM(like_count) like_count
+ FROM posts
+ WHERE deleted_at IS NULL
+ AND post_type <> #{whisper_post_type}
+ GROUP BY topic_id
+ ) AS tbl
+ WHERE topics.id = tbl.topic_id
+ AND topics.like_count <> tbl.like_count
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/spec/models/post_action_spec.rb b/spec/models/post_action_spec.rb
index f4a258dd6a0..12c1d3c0320 100644
--- a/spec/models/post_action_spec.rb
+++ b/spec/models/post_action_spec.rb
@@ -456,6 +456,16 @@ describe PostAction do
expect(notification.notification_type).to eq(Notification.types[:liked])
end
+ it 'should not increase topic like count when liking a whisper' do
+ SiteSetting.set(:enable_whispers, true)
+ post.revise(admin, post_type: Post.types[:whisper])
+
+ PostActionCreator.like(admin, post)
+
+ expect(post.reload.like_count).to eq(1)
+ expect(post.topic.like_count).to eq(0)
+ end
+
it 'should increase the `like_count` and `like_score` when a user likes something' do
freeze_time Date.today