2017-02-21 70 views
0

我有父级和子级模型之间的一对多关系。如何一次性保存父级和嵌套子级?如何在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 

回答

0

解决方案:

  1. 添加accepts_nested_attributes_for模型
  2. 使用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 
相关问题