patternrubyrailsCritical
What is the easiest way to duplicate an activerecord record?
Viewed 0 times
activerecordeasiesttheduplicaterecordwaywhat
Problem
I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the id). What is the simplest way to accomplish this?
I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.
Perhaps something like this:
I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.
Perhaps something like this:
new_record = Record.copy(:id)
Solution
To get a copy, use the dup (or clone for < rails 3.1+) method:
Then you can change whichever fields you want.
ActiveRecord overrides the built-in Object#clone to give you a new (not saved to the DB) record with an unassigned ID.
Note that it does not copy associations, so you'll have to do this manually if you need to.
Rails 3.1 clone is a shallow copy, use dup instead...
#rails >= 3.1
new_record = old_record.dup
# rails < 3.1
new_record = old_record.cloneThen you can change whichever fields you want.
ActiveRecord overrides the built-in Object#clone to give you a new (not saved to the DB) record with an unassigned ID.
Note that it does not copy associations, so you'll have to do this manually if you need to.
Rails 3.1 clone is a shallow copy, use dup instead...
Code Snippets
#rails >= 3.1
new_record = old_record.dup
# rails < 3.1
new_record = old_record.cloneContext
Stack Overflow Q#60033, score: 720
Revisions (0)
No revisions yet.