# Stale object errors

**URL:** <https://www.ruby-forum.com/t/stale-object-errors/65129>\
**Category:** Rails\
**Created:** [August 16, 2006, 12:56pm UTC](https://www.ruby-forum.com/t/stale-object-errors/65129 "2006-08-16T12:56:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jonathan\_del\_Stroth](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/a87d85/32.png) [@Jonathan\_del\_Stroth](https://www.ruby-forum.com/u/Jonathan_del_Stroth)\
**Post date:** [August 16, 2006, 12:56pm UTC](https://www.ruby-forum.com/t/stale-object-errors/65129/1 "2006-08-16T12:56:00Z")

</div>

I’m running into a couple of stale object problems with methods that  
at first glance appear fairly atomic - eg Message.update(params[:id],  
{:body =\> params[:value]})  
Of course, Rails has to instantiate the object & validate it before  
it updates the database, so it’s not actually atomic, hence the  
occasional staleobject error.

So I’ve been wondering about creating a block method looking  
something like:

def update\_volatile\_object  
num\_attempts = 5  
while num\_attempts\>0  
begin  
yield # the block should do something along the lines of  
Message.update(blah)  
break # If we got here, we didn’t raise a stale object error  
rescue ActiveRecord::StaleObjectError =\> e  
num\_attempts -= 1  
end  
end

raise DatabaseSeemsTooDamnBusy if num\_attempts==0  
end

…but it feels like I’m missing something - does Rails supply any  
functionality to do this for me? Any suggestions on how to improve  
the above?

---

<div class="post-metadata">

**Author:** ![Jonathan\_del\_Stroth](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/a87d85/32.png) [@Jonathan\_del\_Stroth](https://www.ruby-forum.com/u/Jonathan_del_Stroth)\
**Post date:** [August 16, 2006, 1:44pm UTC](https://www.ruby-forum.com/t/stale-object-errors/65129/2 "2006-08-16T13:44:03Z")

</div>

On 8/16/06, Jonathan del Strother [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> end
> 
> raise DatabaseSeemsTooDamnBusy if num\_attempts==0  
> end

You shouldn’t be locking the table at all if you find yourself bending  
over  
backward to circumvent the lock.

If you’re working with frequently stale records, consider using  
pessimistic  
locking instead (or rethinking the behavior that requires locking at  
all).

def next!  
transaction do  
task = find(:first, :conditions =\> [‘claimed=?’, false], :lock =\>  
true)  
task.claimed = true  
task.save!  
task  
end  
end

jeremy
