1

There is a simple method:

def get_award(user)
  u = User.find(user).score += 10
  u.save
end

My problem is, is there a potential race condition cause a user get_award twice but get only 10 score? How to avoid it?

Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164

2 Answers2

1

You need to get the 'user' instance, update the score and save it. In your code you're saving the class, not the instantiated object:

def get_award(user)
  u = User.find(user).score += 10
  u.save
end
Matteo Alessani
  • 10,264
  • 4
  • 40
  • 57
0

Yes it is possible.

related questions : How do I avoid a race condition in my Rails app?

You can use two kinds of locking optimistic & pessimistic

http://guides.rubyonrails.org/active_record_querying.html See point No 10

Community
  • 1
  • 1
Gaurav Shah
  • 5,223
  • 7
  • 43
  • 71