Forum: Ruby on Rails StaleObject Merging Example

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
96956a77a329c7f8622e7c81396655fd?d=identicon&s=25 Justin Williams (Guest)
on 2007-03-13 22:01
(Received via mailing list)
Does anyone have an example of how they have dealt with
StaleObjectErrors caused by having optimistic locking enabled?

Ideally I'd like to merge the changes, but I haven't found much in
terms of sample code or documentation on how to do this.

Any help would be appreciated.


- j
5d07490f2d72cfd391289581976c8f1f?d=identicon&s=25 Dave Dumaresq (daved)
on 2007-03-22 05:32
(Received via mailing list)
Hi Justin

I'm interested in this as well. I discovered today that a project I'm
developing threw several StaleObject errors, after I got a report of
discrepancies in views of the data.

I did not even bother writing code to catch the error, eventhough I
went to the trouble to add lock_version fields to all my tables. (I
even wrote a nice little piece of code that reads the schema and
creates lock_versions for all my tables. Got carried away I guess :^)

I'm wondering how the data got stale. I'm certain the customer was the
only person updating the rows. However, I have a piece of code that
could be better written...

In the loop below, packing_item belongs_to rma and I do a separate
save on each table record. The error occurred on the second save. Can
this happen if only one person is running the application?

    packing_slip.packing_items.each_with_index do |item, i|
      item.rma.state_id = PACKED

      item.rma.packing_slip_id =

      item.rma.tracking_number = tracking[item.rma.number]

      item.tracking_number = tracking[item.rma.number]

      # save packing_item!

      # save rma <-- the error happened at this point.!

This topic is locked and can not be replied to.