我想初始化一個對象,但我不想創建對象到數據庫,直到用戶點擊保存。我已經得到這個只與父對象一起工作,但我似乎無法讓我的子對象關聯到父對象,因爲我還沒有父對象的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
如果不插入記錄到數據庫中,您無法「保留」標識。這就是自動遞增數據庫列的工作原理。 – max
@max,是的,我明白 - 我只是用這種方式解釋它,試圖傳達我正在嘗試做的事情。雖然看起來我做得不好。 – daveomcd