1

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.

Mukarram Ali
  • 387
  • 5
  • 24
  • Strong params have nothing to do with that. – ndnenkov Feb 06 '18 at 10:29
  • Possible duplicate of [What is the easiest way to duplicate an activerecord record?](https://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record) – scoudert Feb 06 '18 at 17:31

2 Answers2

3

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

bitsapien
  • 1,753
  • 12
  • 24
2

Simply remove the id:

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

Alternatively, use #dup:

obj2 = obj1.dup
ndnenkov
  • 35,425
  • 9
  • 72
  • 104