2

I'm building a survey app and trying to build a duplication feature so users can duplicate surveys.

What I need to do is duplicate the survey, that survey's questions and each questions answers (multiple choice options, for instance).

Here are my associations:

#Survey
has_many :questions

#Question
belongs_to :survey
has_many :answers

#Answer
belongs_to :question

So, how can I duplicate/clone a survey as well as its associations?

I'm running Rails 3.

Shpigford
  • 24,748
  • 58
  • 163
  • 252

2 Answers2

1

Something like:

#Survey
has_many :questions, :autosave => true   # might need the autosaves, might not

#Question
belongs_to :survey
has_many :answers, :autosave => true

#Answer
belongs_to :question


class Survey < ActiveRecord::Base

  def deep_copy(klass)
     klass.questions.each do |question|
        @question = self.questions.build(:name => question.name)
        question.answers.each do |answer|
           @question.answers.build(:name => answer.name)
        end
     end
  end
end

So to use it, do something like:

@survey_to_copy = Survey.find(123)
@new_survey = Survey.new(:name => "new survey")
@new_survey.deep_copy(@survey_to_copy)
@new_survey.save
Dex
  • 12,527
  • 15
  • 69
  • 90
  • I'm not following this. Can you explain what's going on? I don't see how the survey record gets cloned here. – Shpigford Jun 22 '11 at 20:16
  • Definitely didn't work. It set the `survey_id` of each original question to the newly created survey instead of actually cloning the questions. – Shpigford Jun 22 '11 at 20:26
  • Plus it didn't actually clone any of the original survey...it just created a new survey without any data. – Shpigford Jun 22 '11 at 20:27
  • Try again with the new edits, basically, you are just copying the stuff over manually. – Dex Jun 22 '11 at 20:35
  • You need to create the Survey first, otherwise I think you need to set the `:autosave => true` option in your associations. – Dex Jun 22 '11 at 20:42
  • That defeats the purpose...I need to duplicate the survey and and its associations. Creating a new survey isn't what I need to do...I need to duplicate it. – Shpigford Jun 23 '11 at 12:06
  • I'm a little confused by your terminology, but see my edits again and play around with it. – Dex Jun 23 '11 at 22:31
0

Not sure if it's Rails 3-compatible, but you should have a look at https://github.com/openminds/deep_cloning