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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.