Rails:复制记录及其多级关联?

发布于 2024-11-16 14:43:46 字数 283 浏览 1 评论 0原文

我正在构建一个调查应用程序并尝试构建复制功能,以便用户可以复制调查。

我需要做的是复制调查、调查的问题和每个问题的答案(例如,多项选择)。

以下是我的关联:

#Survey
has_many :questions

#Question
belongs_to :survey
has_many :answers

#Answer
belongs_to :question

那么,我如何复制/克隆调查及其关联?

我正在运行 Rails 3。

I'm building a survey app and trying to build a duplication feature so users can duplicate surveys.

What I need to do is duplicate the survey, that survey's questions and each questions answers (multiple choice options, for instance).

Here are my associations:

#Survey
has_many :questions

#Question
belongs_to :survey
has_many :answers

#Answer
belongs_to :question

So, how can I duplicate/clone a survey as well as its associations?

I'm running Rails 3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡水深流 2024-11-23 14:43:46

像这样的事情:

#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

Something like:

#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

So to use it, do something like:

@survey_to_copy = Survey.find(123)
@new_survey = Survey.new(:name => "new survey")
@new_survey.deep_copy(@survey_to_copy)
@new_survey.save
最初的梦 2024-11-23 14:43:46

不确定它是否与 Rails 3 兼容,但您应该看看 https://github.com/openminds/deep_cloning

Not sure if it's Rails 3-compatible, but you should have a look at https://github.com/openminds/deep_cloning

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文