Search code examples
mysqlruby-on-rails-3data-structuresnested-setstree-structure

Rails 3, MySQL, tree structure


I need to one of my project use a tree structure. I found this link and I tried it to use. My table structure looks this:

id    
user_id
parent_id
lft
rgt

When I try to create a root, so I will do this:

save_tree = TreeStruct.create!(:user_id => @user.id)

And then I try to add the childern:

  save_tree = TreeStruct.create!(:user_id => @user.id)
  save_tree.move_to_child_of(params[:parent])

But in this moment I am stil over and over again getting the error Couldn't find TreeStruct with id=12. The content of my DB table with the tree structure is here:

+----+---------+-----------+------+------+---------------------+---------------------+
| id | user_id | parent_id | lft  | rgt  | created_at          | updated_at          |
+----+---------+-----------+------+------+---------------------+---------------------+
|  1 |      12 |      NULL |    1 |    2 | 2011-11-30 04:09:41 | 2011-11-30 04:09:41 |
+----+---------+-----------+------+------+---------------------+---------------------+

Could anyone help me, please, what I am still doing wrong? I can't find on the right way to use this gem... Why is there needed ID with the value 12? I though this is not needed...

Million times thanks for every help! I am struggling with this problem already second day and still can't find the main problem


Solution

  • I'd recomment to use the "ancestry" gem -- it's excellent at supporting tree structures. It stores the list of ancestors in a comma-separated string, which makes look-ups very efficient.

    http://railscasts.com/episodes/262-trees-with-ancestry

    https://github.com/stefankroes/ancestry