views:

29

answers:

1

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.

Note: I'm running on Rails 3 Beta 2; that may be a factor here.

Update

This looks like it may be a Rails 3 specific bug; I've created a bug report here.

+2  A: 
u = User.first
u.tickets.size # 12
u2 = u.clone
u2.tickets = u.tickets
u2.tickets.pop
u2.tickets.size # 11    
u.tickets.size  # 12

so, u and u2 have different arrays of tickets now

zed_0xff
I'm getting different results; my associations have identical items after the pop (as they did in my original question).I'm thinking this may be a Rails 3 issue; what version are you running?
Craig Walker
you're right, I'm using 2.3.5
zed_0xff
Thanks for confirming that; I've written this up as a [Rails 3 bug](https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4733-dangerous-association-modifications-on-cloned-activerecord-objects)
Craig Walker