Search code examples
ruby-on-railsrubyactiverecordcloneruby-on-rails-3

Modifying association arrays on cloned ActiveRecord objects


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.


Solution

  • 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