ActiveRecord的:我怎样才能克隆嵌套的关联?

编程入门 行业动态 更新时间:2024-10-19 21:23:38
本文介绍了ActiveRecord的:我怎样才能克隆嵌套的关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前克隆单层关联是这样的:

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

让克隆调查然后克隆了问题与这项调查有关。精细。这工作得很好。

So that clones the Survey then clones the Questions associated with that survey. Fine. That works quite well.

但我有麻烦的是,每道题的has_many 答案。因此,调查的has_many问题其中的has_many答案。

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.

推荐答案

使用 deep_clonable宝石

new_survey = original_survey.clone :include => [:questions => :answers]

更多推荐

ActiveRecord的:我怎样才能克隆嵌套的关联?

本文发布于:2023-10-25 13:57:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527153.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!