user58446
user58446

Reputation: 269

Rails::ActiveRecord preserve auto_increment id in deep copy duplicate

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?

Upvotes: 0

Views: 618

Answers (1)

matthewd
matthewd

Reputation: 4435

dup describes this behaviour:

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

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.

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.

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.)

Upvotes: 2

Related Questions