2

我正在构建一个调查应用程序并尝试构建一个复制功能,以便用户可以复制调查。

我需要做的是复制调查,该调查的问题和每个问题的答案(例如多项选择选项)。

以下是我的联想:

#Survey
has_many :questions

#Question
belongs_to :survey
has_many :answers

#Answer
belongs_to :question

那么,如何复制/克隆调查及其关联?

我正在运行 Rails 3。

4

2 回答 2

1

就像是:

#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

因此,要使用它,请执行以下操作:

@survey_to_copy = Survey.find(123)
@new_survey = Survey.new(:name => "new survey")
@new_survey.deep_copy(@survey_to_copy)
@new_survey.save
于 2011-06-22T19:56:30.387 回答
0

不确定它是否兼容 Rails 3,但你应该看看https://github.com/openminds/deep_cloning

于 2011-07-22T22:48:35.210 回答