2017-04-19 67 views
0

我有以下兩類:Ruby on Rails的 - 如何在沒有與替換另一個HAS_ONE協會:刪除或:破壞

class Dungeon < ApplicationRecord 
     has_one :room 
     ... 
    end 

    class Room < ApplicationRecord 
     belongs_to :dungeon 
     ... 
    end 

我希望能夠用另一個替換地牢的一個房間對象並沒有實際刪除或摧毀地牢的原始房間物件。當我嘗試使用update(room: r),我得到

ActiveRecord::RecordNotSaved: Failed to remove the existing associated room. The record failed to save after its foreign key was set to nil. 

什麼我需要做的是能夠簡單地替換另一個地下城的一個房間?

+0

安置自己的數據庫遷移這兩個對象。你的數據庫中可能有一個外鍵約束。 – zarazan

回答

4

由於Rails 5 belongs_to關聯需要關聯的對象存在(請參閱:PR introducing this behavior)。

這就是說:如果你想保持room雖然它不具有dungeon相關的你有你的belongs_to定義修改爲:

belongs_to :dungeon, optional: true 
+0

這個伎倆。謝謝! – cincospenguinos