I have a simple hierarchy that I’m trying to build.
class Category < ActiveRecord::Base
attr_accessible :name
belongs_to :parent, class_name: "Category"
has_many :children, class_name: "Category", foreign_key: :parent_id
end
I can add categories to a tree and it works fine. However, things do not work as expected when deleting. For example:
root = Category.new(:name => "Root")
child = Category.new(:name => "Child")
child.parent = root
# things are fine to this point. root.children contains child,
# and child.parent is root
root.children.delete child
# at this point root.children is empty, but child.parent is still root
Any ideas what might be happening here? Thanks!
Answer: it’s product.reload
This explanation is the first one I’ve found after hours searching:
https://stackoverflow.com/a/7449957/456280
(Also this is directly related to my question here: Delete in Many to Many Relationship Not Symmetric? )