Skip to content

Commit 1253592

Browse files
committed
1 parent e15fb6e commit 1253592

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

app/models/favorite.rb

+10-4
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,13 @@ def self.destroy_all(hash)
1414

1515
def self.add(post, user)
1616
Favorite.transaction do
17+
User.where(:id => user.id).select("id").lock("FOR UPDATE NOWAIT").first
18+
1719
return if Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post.id).exists?
1820
Favorite.create!(:user_id => user.id, :post_id => post.id)
19-
Post.where(:id => post.id).update_all("fav_count = fav_count + 1")
20-
Post.where(:id => post.id).update_all("score = score + 1") if user.is_gold?
21+
updates = "fav_count = fav_count + 1"
22+
updates = "#{updates}, score = score + 1" if user.is_gold?
23+
Post.where(:id => post.id).update_all(updates)
2124
post.append_user_to_fav_string(user.id)
2225
User.where(:id => user.id).update_all("favorite_count = favorite_count + 1")
2326
user.favorite_count += 1
@@ -28,10 +31,13 @@ def self.add(post, user)
2831

2932
def self.remove(post, user)
3033
Favorite.transaction do
34+
User.where(:id => user.id).select("id").lock("FOR UPDATE NOWAIT").first
35+
3136
return unless Favorite.for_user(user.id).where(:user_id => user.id, :post_id => post.id).exists?
3237
Favorite.destroy_all(:user_id => user.id, :post_id => post.id)
33-
Post.where(:id => post.id).update_all("fav_count = fav_count - 1")
34-
Post.where(:id => post.id).update_all("Score = score - 1") if user.is_gold?
38+
updates = "fav_count = fav_count - 1"
39+
updates = "#{updates}, score = score - 1" if user.is_gold?
40+
Post.where(:id => post.id).update_all(updates)
3541
post.delete_user_from_fav_string(user.id)
3642
User.where(:id => user.id).update_all("favorite_count = favorite_count - 1")
3743
user.favorite_count -= 1

db/structure.sql

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
--
44

55
SET statement_timeout = 0;
6-
SET lock_timeout = 0;
76
SET client_encoding = 'UTF8';
87
SET standard_conforming_strings = on;
98
SET check_function_bodies = false;

0 commit comments

Comments
 (0)