Neil Neil - 7 months ago 13
Ruby Question

Make copy of record and save to database but with unique id

I am trying to make a new record that is an exact copy of an existing record, but I need the new record to of course to have a unique

id
. Meaning: I do not want to copy over the
id
from the existing record to the new record.

Current code

@blog = Blog.new(title: "some title")
@blog.save

@copy_of_existing_blog = Blog.new(@blog.attributes)
@copy_of_existing_blog.save


It returns this error:


ActiveRecord::RecordNotUnique


I understand why it is erroring out. It is attempting to save a record that has a duplicate
id
of an existing record. I just do not know how to make an exact copy of a record, minus the
id
, and save it to the database.

max max
Answer

You need to filter out the ID from the attributes hash. ActiveSupport has a handy Hash#except method which does just this:

Blog.new(@blog.attributes.except("id"))

Additionally you may want to filter out the timestamps as well.