0

我有一个简单的层次结构,我正在尝试构建。

class Category < ActiveRecord::Base
  attr_accessible :name

  belongs_to :parent, class_name: "Category"
  has_many :children, class_name: "Category", foreign_key: :parent_id
end

我可以将类别添加到树中,并且效果很好。但是,删除时事情并没有按预期工作。例如:

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

有什么想法可能在这里发生吗?谢谢!

4

2 回答 2

0

答:是product.reload

这是我在数小时搜索后发现的第一个解释: https ://stackoverflow.com/a/7449957/456280

(这也与我的问题直接相关:Delete in Many to Many Relationship Not Symmetric?

于 2012-09-07T15:53:59.963 回答
0

您可以添加:dependent => :destroyhas_many关系中,这将在父级被销毁时删除父级的子级。如果只有一个孩子被摧毁,你可能不想摧毁父母,对吧?

于 2012-09-06T21:58:15.777 回答