acts_as_nested_set to the rescue!

My prayers have been answered.

    gem install rails --include-dependencies

5 comments ↓

#1 Lyle Troxell on 05.02.05 at 12:18 pm

Yes, but can you get it working? I can’t seem to get a new root to be created. Adding a child to an existing root should be hangeled by the instance method “add_child” - but how do you create a root?

#2 Damon Clinkscales on 05.02.05 at 12:34 pm

Yes Lyle, I did. I’m not sure if this is the best way, but having seen the problem you are talking about, this is what I did: root = Category.new() root.save() root.add_child(root) root.parent_id=nil root.save() I had to go back and re-set the parent to nil and it works.

#3 Will on 05.12.05 at 6:51 pm

Hey, for some reason everyone is getting interested in this little thing I wrote a while back…

The problem is you are typeing to add the root as a child of itself. It should be:

root = Category.new
child = Category.new

root.add_child child

That’s all.

#4 Damon Clinkscales on 05.12.05 at 7:39 pm

Ok, so I was just making it harder than it actually was. Thanks, Will!

#5 Damon Clinkscales on 05.13.05 at 10:56 am

So I tried what Will suggested. But I get two zero nodes, so I reverted back to the code I have above. The code I tried was just: root = Category.new(”parent_id” => nil) root.save() then later cat = Category.new cat.save() root.add_child(cat) But I wind up with this: Root | UYGYRXZECZQKGBVBFRKJ4WSZRMXPSNGR | NULL | 0 | 208 | Child 1 | W5X3GFWGWA62H8KQU3JBNCBZQXVARJGN | UYGYRXZECZQKGBVBFRKJ4WSZRMXPSNGR | 0 | 1 | Child 2 | MJH6VEDTXMS4UY6WDCVVFJW3ZA8ZZ3WG | UYGYRXZECZQKGBVBFRKJ4WSZRMXPSNGR | 2 | 3 | Which doesn’t work because there are two 0 nodes. I also tried putting that add_child after the cat.save() but then it complained “Couldn’t find Category without an ID” The way I am doing it (see my first comment) produces the following: Root | UYGYRXZECZQKGBVBFRKJ4WSZRMXPSNGR | NULL | 0 | 211 | Child 1 | W5X3GFWGWA62H8KQU3JBNCBZQXVARJGN | UYGYRXZECZQKGBVBFRKJ4WSZRMXPSNGR | 3 | 4 | Child 2 | MJH6VEDTXMS4UY6WDCVVFJW3ZA8ZZ3WG | UYGYRXZECZQKGBVBFRKJ4WSZRMXPSNGR | 5 | 6 | Which works for me, so….

Leave a Comment