简体   繁体   中英

Creating a new object from another object's attributes in rails

Before introducing strong params it was working fine. So, on creating a new object using new and passing attributes, id was being set as nil .

But now, when I am creating a new object, obj2 from existing object, obj1's attributes,

id (a primary key) of obj1 is also being copied to obj2.

Like,

obj2 = Post.new obj1.attributes

So, problem arises when I try to save it,

obj2.save

with ActiveRecord::RecordNotUnique error. As both object have the same id.

I have several models with the same use case, so if I use dup or except , I'll have to add the same in each case.

If you want to make a copy of your attributes in a new object, you must use the following (Specific to ActiveRecord) :

obj2 = obj1.dup

This leaves out id , (created|updated)_(at|on) from being duplicated. Also remember that the parent associations live as is in the new object.

For more https://apidock.com/rails/ActiveRecord/Core/dup

Simply remove the id :

obj2 = Post.new obj1.attributes.except('id')

Alternatively, use #dup :

obj2 = obj1.dup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM