Search code examples
ruby-on-railsclone

Rails cloning objects question


Say I have a blog post with comments in rails, how do I clone it so I have another blog post with comments, both stored as new objects in the database with their own ids?

I know about the clone command, but it doesn't seem to copy over the comments - only links to them.

Is there a plugin or an easy way to do this in rails?

Thanks!


Solution

  • Since deep copying/cloning is going to look different for every Model class, it's usually left as an exercise to the developer. Here are two ways:

    1. Override clone (could be dangerous if you don't always want this behavior)

      class Post
      ...
        def clone
          new_post = super
          new_post.comments = comments.collect { |c| c.clone }
          new_post
        end
      ...
      end
      
    2. Create a deep_clone or deep_copy method and call it specifically

      class Post
      ...
        def deep_clone
          new_post = clone
          new_post.comments = comments.collect { |c| c.clone }
          new_post
        end
      ...
      end
      

    Both of these guarantee the returned Post object and all its comments will be distinct entities in db (once you call save on the Post, of course).