@@ -14,10 +14,13 @@ def self.destroy_all(hash)
14
14
15
15
def self . add ( post , user )
16
16
Favorite . transaction do
17
+ User . where ( :id => user . id ) . select ( "id" ) . lock ( "FOR UPDATE NOWAIT" ) . first
18
+
17
19
return if Favorite . for_user ( user . id ) . where ( :user_id => user . id , :post_id => post . id ) . exists?
18
20
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 )
21
24
post . append_user_to_fav_string ( user . id )
22
25
User . where ( :id => user . id ) . update_all ( "favorite_count = favorite_count + 1" )
23
26
user . favorite_count += 1
@@ -28,10 +31,13 @@ def self.add(post, user)
28
31
29
32
def self . remove ( post , user )
30
33
Favorite . transaction do
34
+ User . where ( :id => user . id ) . select ( "id" ) . lock ( "FOR UPDATE NOWAIT" ) . first
35
+
31
36
return unless Favorite . for_user ( user . id ) . where ( :user_id => user . id , :post_id => post . id ) . exists?
32
37
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 )
35
41
post . delete_user_from_fav_string ( user . id )
36
42
User . where ( :id => user . id ) . update_all ( "favorite_count = favorite_count - 1" )
37
43
user . favorite_count -= 1
0 commit comments