Datamapper clone entry with new id

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 "clones" the object as described, but how can this be done so that it uses a different identifier after saving the record, for example.

 # => <Item @id=2 @title="Title 1" ... 
+4
source share
1 answer

clone is going to provide you with a copy of the object, which is actually not the way you want - you just want to duplicate the entry in db, right? The way I did this with DM in the past looks like this:

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

You can also do this in one line:

 Item.create(item.attributes.merge(:id => nil)) 
+7
source

Source: https://habr.com/ru/post/1307368/


All Articles