When I clone a simple object in ruby-1.9.2-p290, everything looks OK
class Klass
attr_accessor :str
end
s1 = Klass.new #=> #<Klass:0x401b3a38>
s1.str = "Hello" #=> "Hello"
s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello">
s2.str = "Hello world" #=> "Hello world"
s2 #=> #<Klass:0x00000100977c40 @str="Hello world">
s1 #=> #<Klass:0x00000100993fa8 @str="Hello">
But when I clone an ActiveRecord object then something strange happens:
I am using the rails 3.1.8. Loading development environment (Rails 3.1.8). When I start the 'rails console'.
ruby-1.9.2-p290 :001 > chair = Chair.new(:code => 'code', :description => 'The Description')
#=> #<Chair id: nil, code: "code", description: "The Description", user_id: nil, created_at: nil, updated_at: nil>
ruby-1.9.2-p290 :002 > chair_clone = chair.clone
#=> #<Chair id: nil, code: "code", description: "The Description", user_id: nil, created_at: nil, updated_at: nil>
ruby-1.9.2-p290 :003 > chair_clone.description = "Update description"
#=> "Update description"
ruby-1.9.2-p290 :004 > chair_clone
#=> #<Chair id: nil, code: "code", description: "Update description", user_id: nil, created_at: nil, updated_at: nil>
ruby-1.9.2-p290 :005 > chair
#=> #<Chair id: nil, code: "code", description: "Update description", user_id: nil, created_at: nil, updated_at: nil>
Isn't it strange that the description attribute of the original object 'chair' is also updated.
I found the following warning in the http://apidock.com/ruby/Object/clone doc
Change in clone for ActiveRecord objects in ruby-1.9.3
I noticed that cloning an active record object in ruby-1.9.3 and then changing an attribute on the original object will actually change the cloned object as well. This was not the case in ruby-1.9.2.
Is there already a solution available for this issue ?
Thanks in advance for any feedback.
Joost