Rails ActiveRecord supports duplicating objects in order to create new objects. Sometimes we need to create a duplicate copy of ActiveRecord object and update a few attributes and then save as a new record. This can be achieved with ActiveRecord::Core#dup method.
Let’s take an example to understand this. Let’s say we have a model
Post as given below.
Duplicating ActiveRecord object
Now, suppose we need to create a new post copied
from some older post and just update
published_at attribute of the post
and create a new record from the same.
We can use ActiveRecord::Core#dup method for the same.
The post has values as given below.
Calling dup on
This will create a new
Post without an
copy over all the other attributes of
The newly created object will look like as given below.
As we can see
dup has created a new ActiveRecord object
by removing value of
Points to remember
ActiveRecord::Core#dupis a shallow copy of original object
- It does not include ActiveRecord associations in a newly created object
- The new object is treated as a new ActiveRecord model object
ActiveRecord dup vs clone
There is a subtle difference between
created a shallow copy.
It’s similar to clone in
Whenever value of an attribute in
clonedobject is changed, it’ll be changed in original object as well.
Post object described above to illustrate this.
clone post object as given below.
Now, if we check
object_id of objects
cloned_post are difference.
If we change
title attribute of
it will be changed in in
post object as well.
Let’s print original
Thus, we should be understand this difference between
methods on ActiveRecord model objects to use them.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox