从重复对象中删除所有关联

Delete all associations from duplicated object

使用 object_dup = object.dup 复制对象时,将复制所有关联。

object_dup.foos == object.foos

我想duplicate/clone object 没有它的关联,或者复制后删除所有关联。我想销毁 object_dup 上的所有重复关联。只创建一个新对象可能更容易,但复制使我免于 属性-setting-hell.

这可能吗?

实际上.dup方法并没有复制关联,它只是复制外键(父)。

示例:

# Original
my_post = Post.first
=> #<Post id: 1, title: 'blabla', category_id: 10>

# Duplicate
my_post.dup
=> #<Post id: nil, title: 'blabla', category_id: 10>

# Have the same category_id (10)

我在没有某些属性的情况下进行复制的最佳方式:

Post.new(my_post.attributes.slice('titles'))
=> #<Post id: nil, title: 'blabla', category_id: nil>

这里我们创建一个新的空 Post,使用 my_post.attributes 获取原始 post 属性,使用 slice('title') 仅切片我们想要的属性(接受多个属性,示例: slice('title', 'content', 'tags'))

.dup Documentation

.slice Documentation