Inside a Rails 2.3.x application, I want to update a record every time users click on a specific link.
For eg. visiting www.sito.com/tracks/1 I update a record like this:
r = Record.find(params[:id])
r.views = r.views + 1
r.save
Here are my doubts:
- If 2 users visit the link at the same time, what happen? Probably the app is already updating the record... but what happen to the second request?
UPDATE:
Using a combination of Optimistic Locking, I did this:
Added a "lock_version" column to Record table
Changed the code into this:
Record.transaction do
begin
@record.update_attributes(:views => @record.views + 1)
rescue ActiveRecord::StaleObjectError
retry
end
end