views:

696

answers:

3

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

+3  A: 
f2 = Foo.new( f1.attributes )
f2.save

or in one:

f2 = Foo.create( f1.attributes )
bjelli
you win for being first. MANY thanks for the help to both of you!!! Genius!
THIS WILL NOT WORK!all attributes that are not in attr_accessible, or are in attr_protected will be lost! or if you are using one of the attribute protection plugins will result in an exception thrown!
Vitaly Kushner
+1  A: 

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
Shadwell
+9  A: 

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

@bar = @foo.clone

@bar.save

Vitaly Kushner