views:

25

answers:

1

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

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" ...

A: 

clone is going to give you an object copy, which isn't really what you want - you want to just duplicate the record in the db, correct? The way I have done this with DM in the past is like so:

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

You can also do it in one line:

Item.create(item.attributes.merge(:id => nil))
Tobias Crawley
Top man, thank you so much!
BouncePast