Neil
Neil

Reputation: 5178

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.

Upvotes: 3

Views: 1921

Answers (1)

max
max

Reputation: 102218

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.

Upvotes: 10

Related Questions