Modifying association arrays on cloned ActiveRecord objects
Posted
by Craig Walker
on Stack Overflow
See other posts from Stack Overflow
or by Craig Walker
Published on 2010-05-30T04:27:47Z
Indexed on
2010/05/30
4:32 UTC
Read the original article
Hit count: 286
I have an ActiveRecord model class Foo
that has_many Bar
. I want to clone a Foo (to get duplicates of most of its attributes) and then modify its Bar instances.
This is a problem because cloned ActiveRecord instances share the same associated array; changes to one affect the other.
f1 = Foo.new
b = Bar.new
f1.bars << b
f2 = f1.clone
f2.bars.includes? b # true
f1.bars.clear
f2.bars.includes? b # now false
The real problem is that I can't detach the bars arrays from either Foo:
f1.bars << b
f2.bars.includes? b # true
f2.bars = []
f2.bars.includes? b # now false
f1.bars.includes? b # now also false
If I could do that, then I could replace the Bars as I wanted to. However, any change to one Foo seems to affect the other.
© Stack Overflow or respective owner