user94154
user94154

Reputation: 16564

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

Upvotes: 45

Views: 34436

Answers (5)

Foram
Foram

Reputation: 623

You can make duplicate record in rails like

@bar = @foo.dup
@bar.save!

Upvotes: 4

Vitaly Kushner
Vitaly Kushner

Reputation: 9455

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

@bar = @foo.clone

@bar.save

Upvotes: 61

mydoghasworms
mydoghasworms

Reputation: 18591

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?

Upvotes: 83

bjelli
bjelli

Reputation: 10070

a wrong way to do this would be:

f2 = Foo.new( f1.attributes )     # wrong!
f2.save                           # wrong!

or in one line, but still wrong:

f2 = Foo.create( f1.attributes )  # wrong!

see comments for details

Upvotes: 3

Shadwell
Shadwell

Reputation: 34774

You could use the built-in attributes methods that rails provides. E.g.

f2 = Foo.new(f1.attributes)

or

f2 = Foo.new
f2.attributes = f1.attributes

Upvotes: -2

Related Questions