【发布时间】:2012-08-19 16:07:01
【问题描述】:
当我在 ruby-1.9.2-p290 中克隆一个简单对象时,一切正常
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">
但是当我克隆一个 ActiveRecord 对象时,会发生一些奇怪的事情:
我正在使用 rails 3.1.8。 加载开发环境(Rails 3.1.8)。 当我启动“rails 控制台”时。
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>
原来物体“椅子”的描述属性也更新了,这不是很奇怪吗。
我在http://apidock.com/ruby/Object/clone 文档中发现了以下警告
ruby-1.9.3 中 ActiveRecord 对象的克隆更改
我注意到在 ruby-1.9.3 中克隆一个活动记录对象,然后更改原始对象的属性实际上也会更改克隆对象。在 ruby-1.9.2 中情况并非如此。
是否已经有针对此问题的解决方案?
提前感谢您的任何反馈。
约斯特
【问题讨论】:
标签: ruby ruby-on-rails-3 activerecord clone