title: ActiveRecord: How can I clone nested associations?
body: <p>I'm currently cloning a single-level association like this:</p>
  
  <pre><code>class Survey &lt; ActiveRecord::Base
    def duplicate
      new_template = self.clone
      new_template.questions &lt;&lt; self.questions.collect { |question| question.clone } 
      new_template.save   
    end
  end
  </code></pre>
  
  <p>So that clones the <code>Survey</code> then clones the <code>Questions</code> associated with that survey. Fine. That works quite well.</p>
  
  <p>But what I'm having trouble with is that each question <code>has_many</code> <code>Answers</code>. So <code>Survey has_many Questions which has_many Answers</code>.</p>
  
  <p>I can't figure out how to clone the answers properly. I've tried this:</p>
  
  <pre><code>def duplicate
    new_template = self.clone
  
    self.questions.each do |question|
      new_question = question.clone
      new_question.save
  
      question.answers.each do |answer|
        new_answer = answer.clone
        new_answer.save
        new_question.answers &lt;&lt; answer
      end
  
      new_template.questions &lt;&lt; question
    end
  
    new_template.save   
  end
  </code></pre>
  
  <p>But that does some weird stuff with actually replacing the original answers then creating new ones, so ID's stop matching correctly.</p>