4
class Item
    include DataMapper::Resource

    property :id, Serial
    property :title, String
end

item = Item.new(:title => 'Title 1') # :id => 1
item.save
item_clone = Item.first(:id => 1).clone
item_clone.save

# => <Item @id=1 @title="Title 1" ...

This does "clone" the object as described but how can this be done so it applies a different ID once the record is saved, e.g.

# => <Item @id=2 @title="Title 1" ...
4

1 回答 1

7

clone会给你一个对象副本,这不是你真正想要的——你只想复制数据库中的记录,对吗?我过去用 DM 做这件事的方式是这样的:

new_attributes = item.attributes
new_attributes.delete(:id)
Item.create(new_attributes)

您也可以在一行中完成:

Item.create(item.attributes.merge(:id => nil))
于 2010-04-30T17:48:47.700 回答