问题描述
我有两个类,Master
和Slave
. Master
类has_one slave
,Slave
类属于master
.
I have two classes, Master
and Slave
. The Master
class has_one slave
, the Slave
class belongs to master
.
给出两个关联的对象master_a
和slave_a
(其中slave_a
属于master_a
),如何在不破坏数据库中slave_a
的情况下取消链接它们?我本质上需要释放" slave_a
.我尝试过master_a.slave.delete
,它会从数据库中销毁slave_a
.
Given two associated objects, master_a
and slave_a
(where slave_a
belongs to master_a
), how can I unlink them without destroying slave_a
from the database? I essentially need to "free-up" slave_a
. I've tried master_a.slave.delete
, which destroys slave_a
from the database.
我也尝试过master_a.slave.update_attribute(:master_id, nil)
,但是下次调用master_a.save
时,它将重新链接它们.这是否表明我忽略了回调(Master类中有很多回调),或者我只是在使用错误的工具来完成工作?
I've also tried master_a.slave.update_attribute(:master_id, nil)
, but next time master_a.save
is called, it relinks them. Is this indicative of a callback I'm overlooking (of which the Master class has quite a few), or am I just using the wrong tool for the job?
编辑:我应该指定,我不想销毁任何一个对象,而只是销毁这两个特定实例之间的链接.另外,实际的模型实际上并没有称为主模型和从模型,这只是我正在使用的一个示例.
Edit: I should have specified, I do not want to destroy either object, only the link between these two particular instances. Also, the real models are not actually called master and slave, that's just an illustrative example I'm using.
推荐答案
之所以发生这种情况,是因为master
和slave
对象在内存中的保存方式.即使您已更新了从属服务器,主服务器仍认为从属服务器已与它相关联,因为关联的从属对象仍保留在内存中(这通常更有效).重新加载主服务器后,关联将消失.因此,如果您在控制台中执行了此操作,那么您会期望看到以下内容:
This is happening because of the way the master
and slave
object is held in memory. Even though you've updated the slave, the master still thinks the slave is associated with it as the associated slave object is still held in memory (this is usually more efficient). When the master is reloaded, the association will disappear. So, if you did this in the console you'd expect to see something like this:
master = Master.find(123)
=> <master object>
master.slave.update_attribute(:master_id, nil)
=> true
master.slave
=> <slave object>
master.reload
OR
master = Master.find(123)
master.slave
=> nil
这篇关于Rails 3 has_one关联:取消关联对象的链接而不会破坏它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!