初始化关联模型的对象

时间:2013-05-16 16:16:44

标签: ruby-on-rails ruby-on-rails-3 rails-activerecord

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

答题卡

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实例时,我也可以生成它所有的依赖模型?

1 个答案:

答案 0 :(得分: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