如何在rails中同时创建父模型和子模型

时间:2017-02-21 09:34:11

标签: ruby-on-rails activerecord

我在父母和孩子模型之间有一对多的关系。如何一次保存父级和嵌套子级?

本质。完成以下

# 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

1 个答案:

答案 0 :(得分:0)

解决方案:

  1. 在模型中添加accepts_nested_attributes_for
  2. 在控制器中使用children_attributes
  3. 代码:

    # 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
    
相关问题