在一对多关系中保存多个子记录,其中'one'接受_ented_attributes_for为'many'

时间:2011-06-20 17:55:33

标签: ruby-on-rails

Business has_many Hours and Business还接受_nested_attributes_for Hours

创建商业记录时,它还应自动创建7小时记录,每周记录一次。

你会怎么做?

我想我可以在Business中创建一个after_save回调,然后调用一个创建小时记录的小时方法。

或许我可以在生成7小时对象数组的小时中覆盖'new',然后类似于: b = Business.create b.hours.create

但也许有更好的方法。什么可能是最好的方法?

1 个答案:

答案 0 :(得分:0)

我觉得你的第一个选择会更好。

after_save :create_hours

def create_hours
  7.times { self.hours.create }
end

当然,你想要添加到那里,取决于你需要在那里发生多少逻辑。