From 69facb22b193019ca78d757195f760cdd29ed3fa Mon Sep 17 00:00:00 2001 From: evazion Date: Sat, 8 Jan 2022 13:42:49 -0600 Subject: [PATCH] Fix #4265: Negative favorite counts. There were 2176 users with incorrect favorite counts, and it stopped after user id 522393, so this must have been an old bug. --- app/models/user.rb | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index e143abb2f..94df37b02 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -540,7 +540,7 @@ class User < ApplicationRecord end end - module CountMethods + concerning :CountMethods do def wiki_page_version_count wiki_page_versions.count end @@ -599,6 +599,22 @@ class User < ApplicationRecord ) end end + + class_methods do + def fix_favorite_counts! + User.find_by_sql(<<~SQL.squish) + UPDATE users + SET favorite_count = true_count + FROM ( + SELECT user_id, COUNT(*) AS true_count + FROM favorites + GROUP BY user_id + ) true_counts + WHERE users.id = user_id AND users.favorite_count != true_count + RETURNING users.* + SQL + end + end end module SearchMethods @@ -662,7 +678,6 @@ class User < ApplicationRecord include EmailMethods include ForumMethods include ApiMethods - include CountMethods extend SearchMethods def initialize_attributes