# Implementing Optimistic Offline Lock - How?

**URL:** <https://www.ruby-forum.com/t/implementing-optimistic-offline-lock-how/57487>\
**Category:** Rails\
**Created:** [April 11, 2006, 12:57pm UTC](https://www.ruby-forum.com/t/implementing-optimistic-offline-lock-how/57487 "2006-04-11T12:57:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gkogler](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/ba9def/32.png) [@gkogler](https://www.ruby-forum.com/u/gkogler)\
**Post date:** [April 11, 2006, 12:57pm UTC](https://www.ruby-forum.com/t/implementing-optimistic-offline-lock-how/57487/1 "2006-04-11T12:57:43Z")

</div>

I understand that ActiveRecord supports the “optimistic offline  
lock”-pattern through magic fields (created\_at, updated\_at). However, a  
scaffolded CRUD-Controller doesn’t generate the necessary code to  
support this feature (the model state gets lost between two action  
calls).

What is the best practice to prevent users from overwriting objects with  
outdated data ?

---

<div class="post-metadata">

**Author:** ![gkogler](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/ba9def/32.png) [@gkogler](https://www.ruby-forum.com/u/gkogler)\
**Post date:** [April 11, 2006, 5:47pm UTC](https://www.ruby-forum.com/t/implementing-optimistic-offline-lock-how/57487/2 "2006-04-11T17:47:28Z")

</div>

On 4/11/06, Gernot K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I understand that ActiveRecord supports the “optimistic offline  
> lock”-pattern through magic fields (created\_at, updated\_at). However, a  
> scaffolded CRUD-Controller doesn’t generate the necessary code to  
> support this feature (the model state gets lost between two action  
> calls).
> 
> What is the best practice to prevent users from overwriting objects with  
> outdated data ?

Actually, it’s via the “lock\_version” column. created\_at and  
updated\_at just handle timestamping.

Create an integer column in your table, and give it a default value of  
0 (important). Optimistic locking will be enabled automatically.  
If you have a legacy table or a specific naming convention, you can use:  
class Example \< ActiveRecord::Base  
set\_locking\_column :some\_other\_name  
end  
…to override the ‘magic’ name.

It should work fine with scaffold code. If you need specific handling  
or a particular message when the lock stops some activity from  
happening, you should rescue StaleObjectError in your controller.

def some\_action  
begin  
@whatever.save!  
flash[:notice] = “All systems go.”  
rescue StaleObjectError  
flash[:error] = “Someone else is already using this thingy.”  
end  
end

–Wilson.
