update_Attributes stale Object error

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

On 8 Feb 2008, at 23:16, [email protected] 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

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