Use transaction when favoriting to prevent post from being half-favorited
This commit is contained in:
@@ -12,6 +12,7 @@ class Favorite < ActiveRecord::Base
|
|||||||
end
|
end
|
||||||
|
|
||||||
def self.add(post, user)
|
def self.add(post, user)
|
||||||
|
Favorite.transaction do
|
||||||
return if Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post.id).exists?
|
return if Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post.id).exists?
|
||||||
Favorite.create(:user_id => user.id, :post_id => post.id)
|
Favorite.create(:user_id => user.id, :post_id => post.id)
|
||||||
Post.update_all("fav_count = fav_count + 1", {:id => post.id})
|
Post.update_all("fav_count = fav_count + 1", {:id => post.id})
|
||||||
@@ -22,8 +23,10 @@ class Favorite < ActiveRecord::Base
|
|||||||
# post.fav_count += 1 # this is handled in Post#clean_fav_string!
|
# post.fav_count += 1 # this is handled in Post#clean_fav_string!
|
||||||
post.score += 1 if user.is_gold?
|
post.score += 1 if user.is_gold?
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def self.remove(post, user)
|
def self.remove(post, user)
|
||||||
|
Favorite.transaction do
|
||||||
return unless Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post.id).exists?
|
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.destroy_all(:user_id => user.id, :post_id => post.id)
|
||||||
Post.update_all("fav_count = fav_count - 1", {:id => post.id})
|
Post.update_all("fav_count = fav_count - 1", {:id => post.id})
|
||||||
@@ -34,4 +37,5 @@ class Favorite < ActiveRecord::Base
|
|||||||
post.fav_count -= 1
|
post.fav_count -= 1
|
||||||
post.score -= 1 if user.is_gold?
|
post.score -= 1 if user.is_gold?
|
||||||
end
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user