This project is archived and is in readonly mode.

#4733 ✓ duplicate
Craig S Walker

Dangerous association modifications on cloned ActiveRecord objects.

Reported by Craig S Walker | May 30th, 2010 @ 05:40 PM

When you clone an ActiveRecord object, the association arrays for the original and cloned objects are inextricably linked. Modifications to one impact the other, and I cannot find any means to prevent this.

Say we have two models, Foo and Bar. Foo has_many Bar. If I have foo1 and clone it to make foo2, changes to foo1.bar are reflected in foo2.bar. Assigning a new instance of Array to Foo.bar does not change this.

foo1 = Foo.new
bar = Bar.new
foo1.bars << bar
foo2 = foo1.clone
foo2.bars.includes? bar    # true
foo1.bars.clear
foo2.bars.includes? bar    # now false

foo1.bars << bar
foo2.bars.includes? bar    # true
foo2.bars = []
foo2.bars.includes? b    # now false
foo1.bars.includes? b    # now also false

Also, while I was investigating this, I noticed that foo1.bars.equal? foo2.bars returns false, but foo1.bars.object_id == foo2.bars.object_id returns true. Since the two associations certainly behave like they're the same object, this suggests that .equal? is returning an incorrect value.

I originally posted this issue to Stack Overflow. On there I got a response from another user that suggests that this is a Rails 3-specific problem. I'm using Rails 3 Beta 2 on MRI 1.8.7.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Tickets have moved to Github

The new ticket tracker is available at https://github.com/rails/rails/issues

Shared Ticket Bins

People watching this ticket

Referenced by

Pages