I have a model Foo
with attributes id, name, location
. I have an instance of Foo
:
f1 = Foo.new f1.name = "Bar" f1.location = "Foo York" f1.save
I would like to copy f1
and from that copy, create another instance of the Foo
model, but I don't want f1.id
to carry over to f2.id
(I don't want to explicitly assign that, I want the db to handle it, as it should).
Is there a simple way to do this, other than manually copying each attribute? Any built in functions or would writing one be the best route?
Thanks
You generally use #clone if you want to copy an object including its internal state. This is what Rails is using with its #dup method on ActiveRecord. It uses #dup to allow you to duplicate a record without its "internal" state (id and timestamps), and leaves #clone up to Ruby to implement.
In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance. When using dup, any modules that the object has been extended with will not be copied.
ActiveModel::Model allows implementing models similar to ActiveRecord::Base . class EmailContact include ActiveModel::Model attr_accessor :name, :email, :message validates :name, :email, :message, presence: true def deliver if valid? #
Ruby does provide two methods for making copies of objects, including one that can be made to do deep copies. The Object#dup method will make a shallow copy of an object. To achieve this, the dup method will call the initialize_copy method of that class. What this does exactly is dependent on the class.
As per the following question, if you are using Rails >= 3.1, you can use object.dup
:
What is the easiest way to duplicate an activerecord record?
This is what ActiveRecord::Base#clone method is for:
@bar = @foo.clone @bar.save
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With