Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Dangerous association modifications on cloned ActiveRecord objects.

#4733

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.

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

State: duplicate
Milestone: none
Assigned to: nobody
Importance: Low