本文介绍了在Rails的复制模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型富
带属性的 ID,名称,位置
。我有一个实例富
:
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
我想复制 F1
,并从该副本,创建富
模式的另一个实例,但我不想 f1.id
来结转到 f2.id
(我不想明确指定了,我想分贝来处理它,因为它应该)。
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?
感谢
推荐答案
这是什么的ActiveRecord :: Base的#克隆一>方法是:
@bar = @foo.clone
@bar.save
这篇关于在Rails的复制模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!