From 64d11f0587677afbdda5fa6de117a2c2533aade1 Mon Sep 17 00:00:00 2001 From: Rodrigo Alvarez Date: Mon, 5 Jul 2010 22:22:03 +0800 Subject: [PATCH] Added support for parent_id setter with blank value --- lib/mongoid_acts_as_tree.rb | 10 ++++++++-- test/test_tree.rb | 9 +++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/mongoid_acts_as_tree.rb b/lib/mongoid_acts_as_tree.rb index e4fff75..1537d3e 100644 --- a/lib/mongoid_acts_as_tree.rb +++ b/lib/mongoid_acts_as_tree.rb @@ -31,8 +31,14 @@ def acts_as_tree(options = {}) self.class_eval do define_method "#{parent_id_field}=" do | new_parent_id | - new_parent = self.class.find new_parent_id - new_parent.children.push self, false + if new_parent_id.present? + new_parent = self.class.find new_parent_id + new_parent.children.push self, false + else + self.write_attribute parent_id_field, nil + self[path_field] = [] + self[depth_field] = 0 + end end end diff --git a/test/test_tree.rb b/test/test_tree.rb index 2d53cd5..616d855 100644 --- a/test/test_tree.rb +++ b/test/test_tree.rb @@ -89,6 +89,15 @@ class TestMongoidActsAsTree < Test::Unit::TestCase assert more_deep_child.ancestors.include? child assert more_deep_child.ancestors.include? parent end + + should "assign blank parent_id" do + @child_1.parent_id = '' + @child_1.save + + assert_nil @child_1.reload.parent_id + assert_equal 0, @child_1.depth + assert_equal [], @child_1.path + end context "node" do should "have a root" do