Let\'s say I have three Active Record models:
class Tissue
has_many :boogers, as: :boogerable, dependent: :destroy
end
class Finger
has_many :boogers, as: :
First, you need to know that the ActiveRecord destroy
method uses the object's :id
field when it needs to destroy it. And that the dependent: :destroy
option will trigger the destroy
method upon all objects that are assciated with the current object.
I assume that you're doing something like this:
f = Finger.find(finger_id)
t = Tissue.find(tissue_id)
f.boogers[0].boogerable = t
f.boogers[0].save!
f.destroy
The dependent: :destroy
statement means that when destroy
is called upon f
, it will also be called upon all boogers that are associated with f
. And since f
and its boogers are loaded into memory, the f.booger[0]
object still exists in the array of f.boogers
which will have each of its elements, including boogers[0]
, destroyed when f
is destroyed.
The solution of this case is that you hit f.boogers.reload
to update the array before calling f.destroy
.
Also, please note that when you destroy f
, all associated boogers
will be destroy
ed as well, is that really what you want? destroy the finger with all remaining associated boogers
when one of them is transferred to something else?