Reputation: 28081
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?
Upvotes: 1
Views: 79
Reputation: 5279
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
Upvotes: 0
Reputation: 10412
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
Upvotes: 1