2

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.

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

3

Simply remove the id:

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

Alternatively, use #dup:

obj2 = obj1.dup

2 Comments

Thanks. But I did that actually. But I don't want to add except everywhere. Isn't this is a property of new method to create a new object?
@MukarramAli check out #dup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.