From 85e1ae3c9b9f8aa6c961f57338e572dab3767ce4 Mon Sep 17 00:00:00 2001 From: evazion Date: Sun, 9 Jan 2022 19:30:46 -0600 Subject: [PATCH] favorites: fix posts with incorrect fav_count fields. There were about 4000 posts with an incorrect fav_count. --- script/fixes/087_fix_post_fav_counts.rb | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100755 script/fixes/087_fix_post_fav_counts.rb diff --git a/script/fixes/087_fix_post_fav_counts.rb b/script/fixes/087_fix_post_fav_counts.rb new file mode 100755 index 000000000..1dac66bca --- /dev/null +++ b/script/fixes/087_fix_post_fav_counts.rb @@ -0,0 +1,26 @@ +#!/usr/bin/env ruby + +require_relative "base" + +with_confirmation do + # Fix posts that have a non-zero fav_count but no favorites. + records = Post.where("fav_count != 0").where.not(id: Favorite.select(:post_id).distinct) + puts "Fixing #{records.size} records" + records.update_all(fav_count: 0) +end + +with_confirmation do + # Fix posts that have a fav_count inconsistent with the favorites table. + records = Post.find_by_sql(<<~SQL.squish) + UPDATE posts + SET fav_count = true_count + FROM ( + SELECT post_id, COUNT(*) AS true_count + FROM favorites + GROUP BY post_id + ) true_counts + WHERE posts.id = post_id AND posts.fav_count != true_count + RETURNING posts.* + SQL + puts "Fixing #{records.size} records" +end