如何在rails中同时创建父级和子级模型
问题描述:
我有父级和子级模型之间的一对多关系。如何一次性保存父级和嵌套子级?如何在rails中同时创建父级和子级模型
基本上。完成以下
# 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
答
解决方案:
- 添加
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