【问题标题】:Initialize objects of Associated models初始化关联模型的对象
【发布时间】:2013-05-16 16:16:43
【问题描述】:

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

答题卡

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 哦,这很有趣!我不知道这样的事情存在。基于此,我是否正确地说,如果我添加了我可以将回调添加到 answer_section 并且这也会创建我所有的答案?
    • 是的,你可以,用它更新了答案。所以现在你创建AnswerSheet.new,你将获得每个答案表对象的 4 个 answer_sections 并且每个 answersection 对象将有 2 个答案。干杯!
    • 请注意,如果您使用的模型只有一个 belongs_to 关联(例如与模型 Post 关联)self.post 属性在初始化时将不存在,你需要使用self.build_post。见belongs_to
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    相关资源
    最近更新 更多