在 Rails 中复制模型实例 [英] Copy model instances in Rails

查看:23
本文介绍了在 Rails 中复制模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型 Foo 带有属性 id、name、location.我有一个 Foo 的实例:

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 并从该副本创建 Foo 模型的另一个实例,但我不想要 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#clone 方法用于:

@bar = @foo.clone

@bar.save

这篇关于在 Rails 中复制模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆