Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

question from:https://stackoverflow.com/questions/1262546/copy-model-instances-in-rails

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
633 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...