3

I need to duplicate a record in Rails, then it should be rendered into a new form before of creating the record.

Everything works following this helpful answer, but I'd need to populate the record with has_many_belongs_to_many associations as well

the method dup() let me duplicate everything in the record but its associations, I've also seen there's a gem Amoeba that can do a very versatile deep cloning, but I wonder if there's a simpler solution without using a gem

Community
  • 1
  • 1
Carlo
  • 1,184
  • 4
  • 15
  • 31

1 Answers1

7

Rails does not have built-in deep cloning. In Rails 2.3.x you had clone for cloning active record attributes. In Rails >3 they renamed this method to dup, and its documentation is now missing. However, it's identical to clone and its docs say the following.

Note that this is a "shallow" clone: it copies the object’s attributes only, not its associations. The extent of a "deep" clone is application-specific and is therefore left to the application to implement according to its need.

So if you want to clone associations, you are on your own. In my projects I used a method called replicate for this purpose.

class User < ActiveRecord::Base
  # ...
  def replicate
    replica = dup

    comments.each do |comment|
      replica.comments << comment.dup
    end

    replica
  end
end

Something along these lines.

Max Chernyak
  • 37,015
  • 6
  • 38
  • 43
  • 1
    Shouldn't it be replica.comments << comment.dup? – Toni Apr 14 '14 at 16:37
  • 1
    @Experience right, if you want to dup everything. In my case I was cloning user and moving associated data to the new one. Not 100% sure what OP wanted, but I made the edit as you suggested, cause that does seem more appropriate for the topic. – Max Chernyak Apr 14 '14 at 20:02