2014-06-15 56 views
1

我在模型ProjectQueue之間有一個Rails關聯。一個項目has_many隊列。一個隊列必須有一個項目,因此在project_id上有一個存在驗證Rails的ActiveRecord ::正確的方式來驗證存在的關聯?

假設我想創建一個帶有隊列的新項目。例如,如下所示:

project = Project.new(valid: param, options: here) 
project.queues << Queue.new(other_valid: param, options: here) 
project.save! 

保存將失敗,因爲隊列失敗了project_id出現驗證。

我通常難以解決這個問題的方法是創建一個項目,然後添加隊列,並將整個事務包裝在一個事務中,這樣如果該過程的任何部分失敗,它就會回滾。 ......不知怎的,這似乎比它應該是醜陋的。

那麼,是否還有一種更優雅的方式來創建新項目上的隊列而無需點擊存在驗證,但仍然斷言這些隊列必須有一個項目?

乾杯

+0

在代碼中,分配隊列project.queues時,它會自動分配project_id到該隊列。你確定會失敗嗎? –

回答

2

嘗試使用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 
相關問題