Rails :: ActiveRecord在深拷贝副本中保留auto_increment id [英] Rails::ActiveRecord preserve auto_increment id in deep copy duplicate

查看:70
本文介绍了Rails :: ActiveRecord在深拷贝副本中保留auto_increment id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个包含要处理的模型对象的临时数组。我需要auto_increment主键,但是我不希望保留关联,因为当我从数组中删除对象时,它也会从数据库中删除它(感谢rails,非常不便)。我使用object.dup创建的深层副本的ID标记为nil。如何将它们保留在副本中?

I need to create a temporary array containing model objects to manipulate. I need the auto_increment primary key but I do not want the associations kept because when I remove the object from the array it removes it from the database as well (thanks rails, pretty inconvenient). The deep copies I create using object.dup have the id's marked as nil. How do I keep them in the copy?

推荐答案

dup 描述了此行为:

dup describes this behaviour:


未分配重复对象,并将其视为新记录。

Duped objects have no id assigned and are treated as new records.

dup方法不保留时间戳记(创建|更新)_(在|上)。

The dup method does not preserve the timestamps (created|updated)_(at|on).

之所以这样做,是因为人们几乎总是想复制记录以便将其新副本保存到数据库。

It does that because people almost always want to duplicate the record in order to save a new copy of it to the database.

如果您需要真正相同的副本,请 clone 会做到这一点,但这几乎不再是您所需要的:您几乎可以肯定只想要另一个对同一个对象的引用

If you need a truly identical copy, clone will do that, but it's almost never what you need: you almost certainly just want another reference to the same object.

在这种情况下,根据上下文和其他注释,我知道您的目标是记录列表,例如您可以删除条目而不会影响数据库。

In this case, from context and other comments, I understand that your goal is a list of records, such that you can delete entries and not have it affect the database.

为此,您只需要 to_a 。听起来您当前有一个 ActiveRecord :: Associations :: CollectionProxy (如果不是,则为 ActiveRecord :: Relation )数组,但表示数据库中的关联集:它允许的操作将立即反映在数据库中。 to_a 将为您提供一个代表该列表的普通Ruby数组;然后,您可以根据需要操纵该数组。 (根据该答案的前半部分,在这种情况下,您不需要需要复制单个记录……您只需要将它们存储在一个简单的数组中即可。)

For that, you need only to_a. It sounds like you currently have an ActiveRecord::Associations::CollectionProxy (or if not, an ActiveRecord::Relation), which acts like an array, but represents the associated set in the database: what manipulations it allows, will be immediately reflected in the database. to_a will give you an ordinary Ruby Array representing that list; you can then manipulate that array however you like. (Per the first half of this answer, this is a situation where you do not need to copy the individual records... you just need them in a simple array.)

这篇关于Rails :: ActiveRecord在深拷贝副本中保留auto_increment id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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