I have a relationship like so:
Parent
has_many :children
Child
belongs_to :parent
What I want to do is to delete the parent if there are no more children left. So to do this I have:
Child
before_destroy :destroy_orphaned_parent
def destroy_orphaned_parent
parent.children.each do |c|
return if c != self
end
parent.destroy
end
This works fine, however I also want to cascade the delete of the parent to the child. E.g. I would normally do:
Parent
has_many :children, :dependent => :destroy
This causes the WebRick server to crash when I test it. I assume this is due to an infinite loop of the last child deleting the parent deleting the child etc.
I am starting to think that there is a better way to do this? Anyone have any ideas? Is there a way to prevent this recursion?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…