【问题标题】:Change in clone for ActiveRecord objects in ruby-1.9.2.p290 or ruby-1.9.3ruby-1.9.2.p290 或 ruby​​-1.9.3 中 ActiveRecord 对象的克隆更改
【发布时间】: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


    【解决方案1】:

    不要使用clone,而是使用dup,例如:
    ...
    chair_clone = chair.dup
    ...

    【讨论】:

      【解决方案2】:
      u = User.last
      u.duplicable? # => true
      u2 = u.dup
      u2.email = 'wwwww'
      u.email # => 'megacoder@rambler.ru'
      u2.email # => 'wwwww'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-27
        • 1970-01-01
        • 2011-10-17
        • 2023-03-25
        • 1970-01-01
        • 2011-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多