ActiveRecord:如何克隆嵌套关联? [英] ActiveRecord: How can I clone nested associations?
问题描述
我目前正在克隆这样的单级关联:
I'm currently cloning a single-level association like this:
class Survey < ActiveRecord::Base
def duplicate
new_template = self.clone
new_template.questions << self.questions.collect { |question| question.clone }
new_template.save
end
end
这样就可以克隆Survey
,然后克隆与该调查相关的Questions
.美好的.效果很好.
So that clones the Survey
then clones the Questions
associated with that survey. Fine. That works quite well.
但我遇到的问题是每个问题has_many
Answers
.所以Survey has_many Questions which has_many Answers
.
But what I'm having trouble with is that each question has_many
Answers
. So Survey has_many Questions which has_many Answers
.
我不知道如何正确克隆答案.我试过这个:
I can't figure out how to clone the answers properly. I've tried this:
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 << answer
end
new_template.questions << question
end
new_template.save
end
但这会产生一些奇怪的东西,实际上是替换原始答案然后创建新答案,因此 ID 无法正确匹配.
But that does some weird stuff with actually replacing the original answers then creating new ones, so ID's stop matching correctly.
推荐答案
new_survey = original_survey.clone :include => [:questions => :answers]
这篇关于ActiveRecord:如何克隆嵌套关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!