删除不对称的一对多层次关系?

时间:2012-09-06 21:10:53

标签: ruby-on-rails ruby-on-rails-3

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

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

任何想法可能会发生在这里?谢谢!

2 个答案:

答案 0 :(得分:0)

您可以将:dependent => :destroy添加到has_many关系,这会在父项被销毁时删除父项的子项。如果只有一个孩子被摧毁,你可能不想破坏父母,对吗?

答案 1 :(得分:0)

答案:这是product.reload

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

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