2017-06-23 36 views
0

在父母被保存之前建立2個不同的孩子。我明白,當我寫parent.child.build時,父母的ID會自動提供給孩子。Rails built child但父母身份證號碼爲零

在這裏,第一個孩子是確定的,但第二個有一個folder_id爲零(這是一個的has_many關係)

def create 
    @folder = Folder.new(folder_params) 

    @folder.events.build(scheduler_resource_id: SchedulerResource.where(user: @folder.maker).last.id, 
          start: @folder.production_date.beginning_of_month, end: @folder.production_date.end_of_month) 

    @folder.events.build(scheduler_resource_id: SchedulerResource.where(user: @folder.analyst).last.id, 
          start: @folder.production_date.beginning_of_month, end: @folder.production_date.end_of_month) 

    respond_to do |format| 
     if @folder.save 
     format.html { redirect_to @folder, notice: 'Folder was successfully created.' } 
     format.json { render :show, status: :created, location: @folder } 
     else 
     format.html { render :new } 
     format.json { render json: @folder.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

我不明白,爲什麼父母的ID是不給第二個孩子。

編輯

至於問,這裏是我的事件模型

class Event < ApplicationRecord 
    attr_accessor :date_range 
    belongs_to :scheduler_resource 
    belongs_to :folder 

    accepts_nested_attributes_for :folder 

    def self.select_folder 
    Folder.all.map { |p| ["#{p.client.corporate_name} - #{p.concatenate_mandates} (#{p.status})", p.id] } 
    end 

    def all_day_event? 
    start == start.midnight && self.end == self.end.midnight ? true : false 
    end 

end 
+0

我試過一個類似於你已經共享的例子,它工作正常。從我的觀點來看,問題在於構建「事件」的地方。你能分享你的事件模型嗎? –

+0

'build'可以構建對象的數組,因此,您可以使用數組在單個構建方法中構建這2個對象。像'@books = @ author.books.build([ {published_at:Time.now,book_number:「A12346」}, {published_at:Time.now,book_number:「A12347」} ]''。雖然我不確定這是否能解決您的問題。 – Sajan

+0

@PardeepDhingra我添加了我的模型。唯一不同於任何其他模型的是,我有一個accept_nested_attributes用於更新子表單中的父項。不知道這可能是一個問題here.e – LRP

回答

1

在代碼示例提供@folder#new方法,它不保存記錄創建。未保存的記錄沒有ID,因此沒有ID分配給用#build方法實例化的子記錄。

如果在您撥打events.build時@folder是已保存的記錄,則返回的事件模型將從@folder分配給它的保存的父ID爲folder_id

+0

你是對的,我建立並保存了孩子後,它的工作。謝謝很多 – LRP