2015-10-15 47 views
0

我想初始化一個對象,但我不想創建對象到數據庫,直到用戶點擊保存。我已經得到這個只與父對象一起工作,但我似乎無法讓我的子對象關聯到父對象,因爲我還沒有父對象的ID。我在下面的代碼中做了什麼錯誤?謝謝。如何在不保存父項的情況下在Rails中構建我的對象上的子對象?

def new 

    # Build a new report object with the default type of "draft" and assign it to the player 
    report_options = { player_id: @player.id, 
         author_id: current_user.id, 
         position: @player.position, 
          type: "draft", 
         submitted: false } 

    @report = Report.new(report_options) 

    @skills.where('disabled = (?)',FALSE).each do |skill| 
     # On the line below I get an evaluation record with a proper skill id, 
     # but report_id is `nil` because I'm guessing the report hasn't been 
     # created yet. Is there a way to reserve an id for it without actually 
     # committing the record to the database until the user saves the record? 
     @report.evaluations.build(skill_id: skill.id) 
    end 

    end 
+0

如果不插入記錄到數據庫中,您無法「保留」標識。這就是自動遞增數據庫列的工作原理。 – max

+0

@max,是的,我明白 - 我只是用這種方式解釋它,試圖傳達我正在嘗試做的事情。雖然看起來我做得不好。 – daveomcd

回答

2

評估的模型是不是很清楚,我,但基本上,如果你這樣做

@report.evaluations.build 
@skills.where('disabled = (?)', FALSE).each do |skill| 
    @report.evaluations << Evaluation.new(skill_id: skill.id) 
end 

將添加對象的評價,不保存,不會要求report.id到在添加的時刻存在。

+0

我試過這種方式,但是當我在賦值後做了一個'@ report.evaluations.count'時,它仍然返回零。並且模型評估是報告的有效性,評估屬於技能。 – daveomcd

+1

#count操作與數據庫一起工作,有效地映射到select count(*)SQL操作。它將返回0,因爲關聯尚未保存。嘗試使用#size或#length代替 –

+0

ohhh gotcha謝謝!感謝你的回答。我可以看到它已經填充,但它並沒有顯示在我的頁面視圖中,因爲我猜測是由於我使用了「where」處理你已經提到過的相同情況,因爲它不會工作,因爲它是不是真的在數據庫中。所以我現在要研究如何在我的評估中過濾這些記錄。再次感謝! – daveomcd

相關問題