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.