Lai Yu-Hsuan
Lai Yu-Hsuan

Reputation: 28081

Updating and saving an activerecord field in Rails?

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

Answers (2)

Gaurav Shah
Gaurav Shah

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

Matteo Alessani
Matteo Alessani

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

Related Questions