# Question on Data Concurrency

**URL:** <https://www.ruby-forum.com/t/question-on-data-concurrency/158001>\
**Category:** Rails\
**Created:** [January 17, 2009, 5:47pm UTC](https://www.ruby-forum.com/t/question-on-data-concurrency/158001 "2009-01-17T17:47:40Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![srj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e9c0ed/32.png) [@srj](https://www.ruby-forum.com/u/srj)\
**Post date:** [January 17, 2009, 5:47pm UTC](https://www.ruby-forum.com/t/question-on-data-concurrency/158001/1 "2009-01-17T17:47:40Z")

</div>

In Rails 2.2.2, if I retrieve a record using a Model.find method (any  
of the finds), make changes to it, and then save it, is there a  
possibility that another user (on a different thread, maybe a faster  
machine) could read the same record after me, but update it before  
me? If so, then the other user’s changes would be lost (a data  
concurrency problem).

How does Rails prevent this?

Is there a way to do something like  
Model.save\_only\_if\_updated\_at\_is\_unchanged ?  
Is there a find\_and\_lock, find\_for\_update, or other similar function?

This is different than dirty records, because it is comparing the  
record I have in my session to the same record in the database to  
ensure that _no one else_ changed it.

Thank you,

Steve

---

<div class="post-metadata">

**Author:** ![srj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e9c0ed/32.png) [@srj](https://www.ruby-forum.com/u/srj)\
**Post date:** [January 17, 2009, 5:51pm UTC](https://www.ruby-forum.com/t/question-on-data-concurrency/158001/2 "2009-01-17T17:51:49Z")

</div>

On 17 Jan 2009, at 16:45, srj wrote:

> In Rails 2.2.2, if I retrieve a record using a Model.find method (any  
> of the finds), make changes to it, and then save it, is there a  
> possibility that another user (on a different thread, maybe a faster  
> machine) could read the same record after me, but update it before  
> me? If so, then the other user’s changes would be lost (a data  
> concurrency problem).

Yes

> How does Rails prevent this?
> 
> Is there a way to do something like  
> Model.save\_only\_if\_updated\_at\_is\_unchanged ?  
> Is there a find\_and\_lock, find\_for\_update, or other similar function?

Look up optimistic locking.

Fred
