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

ε祈祈猫儿з 提交于 2019-12-08 03:26:03

问题


I have two classes, Master and Slave. The Master class has_one slave, the Slave class belongs to 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? I essentially need to "free-up" slave_a. I've tried master_a.slave.delete, which destroys slave_a from the database.

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.


回答1:


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


来源:https://stackoverflow.com/questions/23499270/rails-3-has-one-association-unlink-associated-object-without-destroying-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!