如何在Rails模型中克隆单个属性?这不起作用:如何克隆Rails模型属性?
irb(main):309:0> u.reload
=> #<User id: 1, username: "starrychloe", ...
irb(main):310:0> u2 = u.dup
=> #<User id: nil, username: "starrychloe", ...
irb(main):311:0> u2 = u.clone
=> #<User id: 1, username: "starrychloe", ...
irb(main):312:0> u2.username = u.username.clone
=> "starrychloe"
irb(main):313:0> u2.username = 'star'
=> "star"
irb(main):314:0> u.username ############ Changes original
=> "star"
也不是这:
irb(main):320:0> u.reload
=> #<User id: 1, username: "starrychloe", ...
irb(main):321:0> u2 = u.clone
=> #<User id: 1, username: "starrychloe", ...
irb(main):322:0> u2[:username] = u[:username].clone
=> "starrychloe"
irb(main):323:0> u2.username = 'cow'
=> "cow"
irb(main):324:0> u.username ############ Changes original
=> "cow"
#dup
不会复制ID,并#clone
的属性保持参照相同的字符串。 This不会解决我的问题。
使用'dup'工程,不应该改变你原来的实例属性。我已经在Rails 4和Ruby 2上测试过了。'dup'不会复制id,因为它初始化实例的一个新副本,因此不会是db中的同一个对象。 –