alejorivera
alejorivera

Reputation: 935

How can I concisely duplicate an ActiveRecord object and change an attribute?

Can this be done in fewer lines?

clone = self.dup
clone.assign_attributes owner: owner
clone.save

Even two lines would be better than three!

Upvotes: 0

Views: 581

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

I don't know Rails but I assume this would work:

dup.tap { |clone| clone.assign_attributes(owner: owner) }.save

Upvotes: 1

Rob Di Marco
Rob Di Marco

Reputation: 44932

self.class.create(attributes.merge(owner: owner))

Upvotes: 3

Related Questions