我有一个嵌套关联,我有Rubric>指标>题。在这个要点中,您可以看到我正确地逐步完成关联,然后尝试克隆对象及其关联。但是,请注意我有一个klone.questions的空数组。我可以klone.indicators.first.questions
并检索与第一个指标相关的所有问题,但我正在寻找一种方法来检索与量规相关的所有问题(在这种情况下为klone)。
答案 0 :(得分:1)
我假设你正在使用has_many :questions, :through => :indicators
。您使用它的方式是否有可能与深度克隆不兼容?你对klone.indicators.first.questions
有什么看法?
答案 1 :(得分:0)
看起来像deep_clonable无法处理has_many:通过类型关联。我最后这样做是这样做的:
def create
template = Template.find params[:template][:id]
params[:section_ids].each do |section|
@rubric = Rubric.new(template.attributes.merge(:name => template.name))
@rubric.section_id = section
@rubric.save
template.indicator_templates.each do |i|
indicator = Indicator.new(:name => i.name, :rubric_id => @rubric.id)
indicator.save
i.question_templates.each do |q|
question = Question.new(:name => q.name, :indicator_id => indicator.id)
question.save
end
end
end
if @rubric.save
redirect_to rubrics_path, :notice => "Successfully created rubric."
else
render :action => 'new'
end
end
因此,对于我试图克隆的3个模型(Rubrics,Indicators和Questions),我创建了3个基本上模仿这些模型的模型。我称之为模板(用于Rubric),IndicatorTemplate(用于指标)和QuestionTemplate(用于问题)。然后我创建了一个新的Rubric,并逐步完成指示和问题,并在此过程中建立适当的关联。