Commit 8dc47cf764bdac2030f7f77d551e6e8d1bce41bf

Authored by Dhruv Kapadia
1 parent 0d1f1e29

Changing choice loss count update to be atomic, prevent one type of race case

app/models/choice.rb
@@ -22,9 +22,9 @@ class Choice < ActiveRecord::Base @@ -22,9 +22,9 @@ class Choice < ActiveRecord::Base
22 #attr_accessor :data 22 #attr_accessor :data
23 23
24 def lose! 24 def lose!
25 - self.loss_count += 1 rescue (self.loss_count = 1)  
26 - self.score = compute_score  
27 - self.save! 25 + Choice.increment_counter(:loss_count, self.id)
  26 + self.loss_count +=1 # reflect the update just done above, so score is correct
  27 + Choice.update(self.id, :score => compute_score)
28 end 28 end
29 29
30 def win! 30 def win!
spec/models/choice_spec.rb
@@ -108,6 +108,7 @@ describe Choice do @@ -108,6 +108,7 @@ describe Choice do
108 @winning_choice.score.should be_close(67, 1) 108 @winning_choice.score.should be_close(67, 1)
109 end 109 end
110 it "should update score on a loss" do 110 it "should update score on a loss" do
  111 + @losing_choice.reload
111 @losing_choice.score.should be_close(33,1) 112 @losing_choice.score.should be_close(33,1)
112 end 113 end
113 it "should update win count on a win" do 114 it "should update win count on a win" do