# StaleObject Merging Example

**URL:** <https://www.ruby-forum.com/t/staleobject-merging-example/88733>\
**Category:** Rails\
**Created:** [March 13, 2007, 10:01pm UTC](https://www.ruby-forum.com/t/staleobject-merging-example/88733 "2007-03-13T22:01:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rubylover](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8c91f0/32.png) [@rubylover](https://www.ruby-forum.com/u/rubylover)\
**Post date:** [March 13, 2007, 10:01pm UTC](https://www.ruby-forum.com/t/staleobject-merging-example/88733/1 "2007-03-13T22:01:49Z")

</div>

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.

Thanks.

- j

---

<div class="post-metadata">

**Author:** ![rubylover](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8c91f0/32.png) [@rubylover](https://www.ruby-forum.com/u/rubylover)\
**Post date:** [March 22, 2007, 5:32am UTC](https://www.ruby-forum.com/t/staleobject-merging-example/88733/2 "2007-03-22T05:32:25Z")

</div>

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.

Aside…  
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 :^)  
…Back.

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 = packing_slip.id

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

```

[:tracking\_number]

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

```

[:tracking\_number]

```
  # save packing_item
  item.save!

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

```

Dave
