复制活动记录记录的最简单方法是什么? [英] What is the easiest way to duplicate an activerecord record?

查看:43
本文介绍了复制活动记录记录的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制一个 ActiveRecord 对象,更改进程中的单个字段(除了 id).实现这一目标的最简单方法是什么?

I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the id). What is the simplest way to accomplish this?

我意识到我可以创建一个新记录,然后遍历每个字段,逐个字段复制数据 - 但我认为必须有一种更简单的方法来做到这一点.

I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.

也许是这样的:

 new_record = Record.copy(:id)

推荐答案

要获取副本,请使用 clone(或 dup for rails 3.1+)方法:

To get a copy, use the clone (or dup for rails 3.1+) method:

# rails < 3.1
new_record = old_record.clone

#rails >= 3.1
new_record = old_record.dup

然后您可以更改您想要的任何字段.

Then you can change whichever fields you want.

ActiveRecord 覆盖内置的 Object#clone 为您提供具有未分配 ID 的新(未保存到数据库)记录.
请注意,它不会复制关联,因此您必须根据需要手动执行此操作.

ActiveRecord overrides the built-in Object#clone to give you a new (not saved to the DB) record with an unassigned ID.
Note that it does not copy associations, so you'll have to do this manually if you need to.

Rails 3.1 克隆是浅拷贝,请改用 dup...

这篇关于复制活动记录记录的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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