Rails ActiveRecord dup objects
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 post
object
This will create a new Post
without an ID
as nil
and
copy over all the other attributes of post
object.
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 id
attribute.
Points to remember
- The
ActiveRecord::Core#dup
is 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 dup
and clone
methods.
ActiveRecord::Core#clone
created a shallow copy.
It’s similar to clone in Ruby
.
Difference between clone
and dup
Whenever value of an attribute in
cloned
object is changed, it’ll be changed in original object as well.
Let’s use Post
object described above to illustrate this.
Now, let’s clone
post object as given below.
Now, if we check object_id
of objects post
and cloned_post
are difference.
If we change title
attribute of cloned_post
,
it will be changed in in post
object as well.
Let’s print original post
object.
Thus, we should be understand this difference between clone
and dup
methods on ActiveRecord model objects to use them.
References
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox