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 に答える