2017-02-21 51 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 
相關問題