2017-04-19 61 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