2017-02-21 10 views
0

У меня есть отношение «один-много» между родительской и дочерней моделью. Как сохранить родительский и вложенные дети за один раз?Как создать родительские и дочерние модели одновременно в рельсах

По существу. выполните следующие

# 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