开发者

Saving several child records in one-to-many relationship where the 'one' accepts_nested_attributes_for the 'many'

Business has_many Hours and Business also accepts_nested_attributes_for Hours

When a Business record is created, it should also automatically create 7 Hour records, one for each day of the week.

How would you go about this?

I'm thinking I could create an after_save callback in Business that then calls a method in Hours which creates the Hours records.

Or maybe I could 开发者_运维知识库override 'new' in Hours generating an array of the 7 Hour objects, then something like: b = Business.create b.hours.create

But maybe there's a better way. What might be the best approach to this?


I think your better off with your first option.

after_save :create_hours

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

of course you'd want to add to that depending on how much more logic you need to happen there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜