Thursday, October 15, 2009

[Rails] How Does Locking Work?

I've been reading about locking for ActiveRecord, but it seems a
little vague to me. My situation is this: I have a controller that
assigns jobs to people who are logged in. The basic code is:

j = Job.find :first, :conditions => 'employee_id is null'
unless j.nil?
j.employee = current_employee
j.save
end

Of course, this can cause, and has caused a race condition. My
temporary fix was to add :order => 'RAND()', so that the possibility
of a collision is reduced, but the possibility is still there.

It seems the lock! might fix this, but I don't understand what really
happens here. If I lock! the record, what happens to the second
employee that tries to pull the record and save it?

Is there another method I should be looking at?

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate