嘗試使用build方法上的隊列的關聯,就像這樣:
project = Project.new(valid: param, options: here)
project.queues.build(other_valid: param, options: here) //this will build the queue and set its project_id to your current project.
project.save!
只是要確保您的PROJECT_ID具有正確的價值,呼籲project.save!
插入此行之前:
project.queues.each do |queue|
puts queue.project_id
end
那麼,什麼是你錯了r代碼?
project = Project.new(valid: param, options: here) //build a new project - this is not yet persisted, so your id column is nil
project.queues << Queue.new(other_valid: param, options: here) // this line tries to save the queue to the database, does not wait for you to call project.save!
project.save!
當你撥打:
project.queues << Queue.new(other_valid: param, options: here)`
Rails的嘗試到新的隊列保存到數據庫中,但因爲你的項目沒有被保存,queue.project_id
是零所以你的隊列驗證失敗。
如果您嘗試類似於從數據庫中獲取的項目(持久項目),您的代碼將無誤地運行。
如果你仍然想使用類似的東西,就可以添加一個新的隊列,這樣之前保存的項目:
project = Project.new(valid: param, options: here)
if project.save
project.queues << Queue.new(other_valid: param, options: here) //this guarantees that project_id exists
end
在代碼中,分配隊列project.queues時,它會自動分配project_id到該隊列。你確定會失敗嗎? –