0

我有三个模型,定义如下:

答题卡

class AnswerSheet < ActiveRecord::Base
     has_many :answer_sections
     accepts_nested_attributes for :answer_sections
end

回答部分

class AnswerSection < ActiveRecord::Base
     belongs_to :answer_sheet
     has_many :answers
     accepts_nested_attributes_for :answers
end

答案

class Answers < ActiveRecord::Base
    belongs_to: answer_section
end

AnswerSheet我在模型中也定义了以下方法

def self.build_with_answer_sections
    answer_sheet = new  # new should be called on the class e.g. AnswerSheet.new
    4.times do |n|
        answer_sheet.answer_sections.build
    end
answer_sheet
end

我将如何制作它,以便当我制作 AnswerSheet 的新实例时,我也可以生成它的所有依赖模型?

4

1 回答 1

1

您可以使用after_initialize回调

    class AnswerSheet < ActiveRecord::Base
      has_many :answer_sections
      accepts_nested_attributes for :answer_sections
      after_initialize :add_answer_section

      def add_answer_section
        4.times {self.answer_sections.build }
      end
     end

    class AnswerSection < ActiveRecord::Base
      belongs_to :answer_sheet
      has_many :answers
      accepts_nested_attributes_for :answers

      after_initialize :add_answer

     def add_answer
       2.times {self.answers.build}
     end
 end
于 2013-05-16T16:46:55.510 回答