ActiveRecord: How can I clone nested associations?

前端 未结 5 1160
星月不相逢
星月不相逢 2020-12-05 18:17

I\'m currently cloning a single-level association like this:

class Survey < ActiveRecord::Base
  def duplicate
    new_template = self.clone
    new_templ         


        
5条回答
  •  庸人自扰
    2020-12-05 18:23

    You can also alias the rails dup method, as follows:

    class Survey
       has_many :questions, :inverse_of=>:survey, :autosave=>true
       alias orig_dup dup
       def dup
           copy=orig_dup
           copy.questions=questions
           copy
       end
    end
    
    class Questions
       belongs_to :survey, :inverse_of=>:questions
       has_many :answers, :inverse_of=>:question, :autosave=>true
       alias orig_dup dup
       def dup
           copy=orig_dup
           copy.answers=answers
           copy
       end
    end
    
    class Answer
        belongs_to :question
    end
    

    and then you can do this

    aaa = Survey.find(123).dup
    aaa.save
    

提交回复
热议问题