Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy model instances in Rails

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

like image 989
user94154 Avatar asked Aug 11 '09 19:08

user94154


People also ask

How do you duplicate an object in Rails?

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.

What is the difference between the object methods clone and DUP?

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.

What is ActiveModel:: model?

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? #

How do you copy an object in Ruby?

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.


2 Answers

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?

like image 170
mydoghasworms Avatar answered Oct 14 '22 06:10

mydoghasworms


This is what ActiveRecord::Base#clone method is for:

@bar = @foo.clone  @bar.save 
like image 34
Vitaly Kushner Avatar answered Oct 14 '22 07:10

Vitaly Kushner