2016-12-05 19 views
3

鑑於以下車型如何在需要時創建並保存父和子記錄= true?

class Parent 
    has_many :children 
end 
class Child 
    belongs_to :parent, required: true 
end 

是否有可能在同一時間創建家長和孩子?

@parent = Parent.new(valid_attributes) 
@parent.children.build(valid_attributes) 
@parent.save 
@parent.errors.messages 
#=> {:"children.parent"=>["must exist"]} 

刪除required: true允許記錄保存。但是有沒有辦法讓父母和孩子一起保存,同時仍然驗證父母是否存在?

回答

4

您可以使用accepts_nested_attributes_for,在關聯上啓用嵌套屬性允許您一次創建父項和子項。

型號parent.rb

class Parent < ActiveRecord::Base 
    has_many :children 

    #enable nested attributes 
    accepts_nested_attributes_for :children 
end 

型號child.rb

class Child < ActiveRecord::Base 
    belongs_to :parent 
end 

創建和保存你的對象parents_controller.rb

class ParentsController < ApplicationController 

    def new 
    @parent = Parent.new 
    @parent.children.build 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @parent } 
    end 
    end 

    def create 
     #your params should look like. 
     params = { 
     parent: { 
      name: 'dummy parent', 
      children_attributes: [ 
      { title: 'dummy child 1' }, 
      { title: 'dummy child 2' } 
      ] 
     } 
     } 

     #You can save your object at once. 
     @parent = Parent.create(params[:parent]) 

     #Or you can set object attributes manually and then save it. 
     @parent.name = params[:parent][:name] 
     @parent.children_attributes = params[:parent][:children_attributes] 
     @parent.save 
    end 

end 

欲瞭解更多信息: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

+0

你在正確的軌道,但孩子的正常多的是兒童不要孩子的。這在軌道上很重要,因爲它會弄亂變形。還有幾個語法錯誤。 – max

+0

感謝@max指出這一點,我已經更新了我的答案。請讓我知道我在哪裏使用錯誤的語法? – Satendra

+0

看我的編輯。兩個地方的結腸與兒童之間有一段距離。 – max

相關問題