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)

1 行で実行することもできます。

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