docaholic
docaholic

Reputation: 625

Initialize objects of Associated models

I have three models which have been defined as follows:

Answer Sheet

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

Answer Section

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

Answers

class Answers < ActiveRecord::Base
    belongs_to: answer_section
end

I also have the following method defined in the AnswerSheet model

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

How would I go about making it so that when I make a new instance of the the AnswerSheet, I can also generate all it's dependent models as well?

Upvotes: 0

Views: 102

Answers (1)

AnkitG
AnkitG

Reputation: 6568

You can use the after_initialize callback

    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

Upvotes: 1

Related Questions