2011-06-22 32 views
2

我正在構建一個調查應用程序並嘗試構建複製功能,以便用戶可以複製調查。Rails:重複記錄及其多級關聯?

我需要做的是重複調查,調查的問題和每個問題的答案(例如多項選擇選項)。

這裏是我的協會:

#Survey 
has_many :questions 

#Question 
belongs_to :survey 
has_many :answers 

#Answer 
belongs_to :question 

所以,我怎麼可以複製/克隆的調查以及其關聯?

我跑的Rails 3

回答

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 
+0

我不是這樣的。你能解釋一下發生了什麼嗎?我沒有看到調查記錄如何在這裏被克隆。 – Shpigford

+0

肯定沒有工作。它將每個原始問題的'survey_id'設置爲新創建的調查,而不是實際克隆問題。 – Shpigford

+0

再加上它並沒有克隆任何原始調查......它只是創建了一個沒有任何數據的新調查。 – Shpigford