How to copy objects of Ruby model to another one fast in an one-liner

I recently created a new model and wanted to copy all its elements to the new one by keeping the old ones just to be safe, so I figured out a way to do this fast.

Let’s say the old model is called Item and the new one NewItem.

Item.all.each {|i_old| i_no_id = i_old.attributes; i_old.delete(“id”); NewItem.create!(i_no_id)}

or slice it to get only the attributes you want

Item.all.each {|i_old| NewItem.create!(i_old.attributes.slice(:a, :b)}

If copied without deleting the id, it will fail, so we first need to delete it and then send the Hash to the new object’s create method. There could be another way that may improve performance If the data were copied to an array and then batch persisted, but this one took me 5 minutes to create so I think it’s only usable If you have millions of records to copy.

In the end check with

Item.all.count == NewItem.all.count

and

Item.all == NewItem.all

That’s it.

Like what you read? Give Chris Veleris a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.