From 8dc47cf764bdac2030f7f77d551e6e8d1bce41bf Mon Sep 17 00:00:00 2001 From: Dhruv Kapadia Date: Fri, 9 Jul 2010 13:35:48 -0400 Subject: [PATCH] Changing choice loss count update to be atomic, prevent one type of race case --- app/models/choice.rb | 6 +++--- spec/models/choice_spec.rb | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/models/choice.rb b/app/models/choice.rb index f8ca4ba..442edeb 100644 --- a/app/models/choice.rb +++ b/app/models/choice.rb @@ -22,9 +22,9 @@ class Choice < ActiveRecord::Base #attr_accessor :data def lose! - self.loss_count += 1 rescue (self.loss_count = 1) - self.score = compute_score - self.save! + Choice.increment_counter(:loss_count, self.id) + self.loss_count +=1 # reflect the update just done above, so score is correct + Choice.update(self.id, :score => compute_score) end def win! diff --git a/spec/models/choice_spec.rb b/spec/models/choice_spec.rb index c892bbe..11b6e48 100644 --- a/spec/models/choice_spec.rb +++ b/spec/models/choice_spec.rb @@ -108,6 +108,7 @@ describe Choice do @winning_choice.score.should be_close(67, 1) end it "should update score on a loss" do + @losing_choice.reload @losing_choice.score.should be_close(33,1) end it "should update win count on a win" do -- libgit2 0.21.2