我在父母和孩子模型之间有一对多的关系。如何一次保存父级和嵌套子级?
本质。完成以下
# assumed @parent and @children is set
# @parent is attributes for parent
# @children is an array of @child attributes
def create
p = Parent.new @parent
p.what_do_i_do @children # what do I do here?
p.save
end
答案 0 :(得分:0)
解决方案:
accepts_nested_attributes_for
children_attributes
代码:
# model
class Parent < ApplicationRecord
has_many :children
accepts_nested_attributes_for :children
end
# controller
def create
p = Parent.new @parent
p.children_attributes = @children
p.save
end