简体   繁体   English

Rails 3 has_one关联:在不破坏关联对象的情况下取消链接?

[英]Rails 3 has_one association: unlink associated object without destroying it?

I have two classes, Master and Slave . 我有两个班级, MasterSlave The Master class has_one slave , the Slave class belongs to master . Master类具有has_one slaveSlave类属于master

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? 给定两个关联的对象master_aslave_a (其中slave_a属于master_a ),如何在不破坏数据库中slave_a情况下取消链接它们? I essentially need to "free-up" slave_a . 我本质上需要“释放” slave_a I've tried master_a.slave.delete , which destroys slave_a from the database. 我尝试了master_a.slave.delete ,它从数据库中破坏了slave_a

I've also tried master_a.slave.update_attribute(:master_id, nil) , but next time master_a.save is called, it relinks them. 我也尝试过master_a.slave.update_attribute(:master_id, nil) ,但是下次调用master_a.save ,它将重新链接它们。 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? 这是否表示我忽略了回调(Master类中有很多回调),或者我只是在使用错误的工具来完成工作?

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. 另外,实际模型实际上并没有称为主模型和从模型,这只是我正在使用的一个示例。

This is happening because of the way the master and slave object is held in memory. 发生这种情况的原因是master对象和slave对象在内存中的保存方式。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM