# update\_Attributes stale Object error

**URL:** <https://www.ruby-forum.com/t/update-attributes-stale-object-error/128582>\
**Category:** Rails\
**Created:** [February 9, 2008, 12:17am UTC](https://www.ruby-forum.com/t/update-attributes-stale-object-error/128582 "2008-02-09T00:17:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [February 9, 2008, 12:17am UTC](https://www.ruby-forum.com/t/update-attributes-stale-object-error/128582/1 "2008-02-09T00:17:29Z")

</div>

Hi,

IN one of my unit tests I get an ActiveRecord::StaleObjectError:  
Attempted to update a stale object

object.save!

in object I have apart from other stuff an after\_save method, which  
calls  
object.assosication.update\_attributes(…)

If I remove that line from my code my tests succeeds.

Unfortunetly, I do not understand why an update\_attributes call can  
generate an StaleObjectError.

Maybe anybody can explain this to me?

Thanks a lot in advance.  
Volker

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [February 9, 2008, 12:49am UTC](https://www.ruby-forum.com/t/update-attributes-stale-object-error/128582/2 "2008-02-09T00:49:44Z")

</div>

On 8 Feb 2008, at 23:16, removed\_email\_address@domain.invalid wrote:

> object.assosication.update\_attributes(…)
> 
> If I remove that line from my code my tests succeeds.
> 
> Unfortunetly, I do not understand why an update\_attributes call can  
> generate an StaleObjectError.
> 
> Maybe anybody can explain this to me?

You’re using optimistic locking. When using this (ie if you have a  
lock\_version column), if you try to save an object when a newer  
version exists in the database (ie you’re trying to clobber new data  
with an older version) you’ll get that exception.

Fred

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [February 9, 2008, 1:14am UTC](https://www.ruby-forum.com/t/update-attributes-stale-object-error/128582/3 "2008-02-09T01:14:20Z")

</div>

Amazing…

if I do the following:

@parent = Parent.find(1)

child1 = Child.new(:parent =\> @parent);

child1.save!

in after\_save of child1:  
self.parent.update\_attributes(:test =\> ‘Hallo’);

afterwards:  
assert\_not\_nil(child1.parent.test);  
assert\_not\_nil(@parent.test);

The second assert will fail…  
I ve thought all references will go to the same object… but it  
seems that was kind of wrong… Quite ugly…

–  
Volker
