diff --git a/app/models/favorite.rb b/app/models/favorite.rb index 0db481935..545fe9102 100644 --- a/app/models/favorite.rb +++ b/app/models/favorite.rb @@ -4,19 +4,6 @@ class Favorite < ApplicationRecord scope :for_user, lambda {|user_id| where("user_id % 100 = #{user_id.to_i % 100} and user_id = #{user_id.to_i}")} attr_accessible :user_id, :post_id - # this is necessary because there's no trigger for deleting favorites - def self.destroy_all(user_id: nil, post_id: nil) - if user_id && post_id - connection.execute("delete from favorites_#{user_id % 100} where user_id = #{user_id} and post_id = #{post_id}") - elsif user_id - connection.execute("delete from favorites_#{user_id % 100} where user_id = #{user_id}") - elsif post_id - 0.upto(99) do |uid| - connection.execute("delete from favorites_#{uid} where post_id = #{post_id}") - end - end - end - def self.add(post:, user:) Favorite.transaction do User.where(:id => user.id).select("id").lock("FOR UPDATE NOWAIT").first @@ -40,7 +27,7 @@ class Favorite < ApplicationRecord User.where(:id => user.id).select("id").lock("FOR UPDATE NOWAIT").first return unless Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post_id).exists? - Favorite.destroy_all(user_id: user.id, post_id: post_id) + Favorite.for_user(user.id).delete_all(post_id: post_id) Post.where(:id => post_id).update_all("fav_count = fav_count - 1") post.delete_user_from_fav_string(user.id) if post User.where(:id => user.id).update_all("favorite_count = favorite_count - 1") diff --git a/app/models/post.rb b/app/models/post.rb index e1056668f..48acc5676 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1038,7 +1038,9 @@ class Post < ApplicationRecord end def remove_from_favorites - Favorite.destroy_all(post_id: self.id) + favorites.find_each do |fav| + remove_favorite!(fav.user) + end end def remove_from_fav_groups diff --git a/test/unit/post_test.rb b/test/unit/post_test.rb index f1151b706..d2a208102 100644 --- a/test/unit/post_test.rb +++ b/test/unit/post_test.rb @@ -80,6 +80,13 @@ class PostTest < ActiveSupport::TestCase end end + should "decrement the user's favorite count" do + @post.add_favorite!(@post.uploader) + assert_difference(["@post.uploader.reload.favorite_count"], -1) do + @post.expunge! + end + end + should "remove the post from iqdb" do mock_iqdb_service! Post.iqdb_sqs_service.expects(:send_message).with("remove\n#{@post.id}")