mysql - Rails 3、MySQL、树形结构

标签 mysql ruby-on-rails-3 data-structures nested-sets tree-structure

我需要我的一个项目使用树结构。我发现this链接,我尝试使用它。我的表结构如下:

id    
user_id
parent_id
lft
rgt

当我尝试创建根时,我会这样做:

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

然后我尝试添加子项:

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

但此时我仍然一遍又一遍地收到错误无法找到 id=12 的 TreeStruct。我的树形结构数据库表的内容如下:

+----+---------+-----------+------+------+---------------------+---------------------+
| 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 |
+----+---------+-----------+------+------+---------------------+---------------------+

有人可以帮我吗,我仍然做错了什么?我找不到使用这个 gem 的正确方法...为什么需要值为 12 的 ID?我虽然这不需要......

一百万次感谢您的每一次帮助!我第二天就在努力解决这个问题,但仍然找不到主要问题

最佳答案

我建议使用“ancestry” gem ——它在支持树结构方面非常出色。它将祖先列表存储在逗号分隔的字符串中,这使得查找非常高效。

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

https://github.com/stefankroes/ancestry

关于mysql - Rails 3、MySQL、树形结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321120/

相关文章:

mysql - 无法访问 MySQL 数据

mysql - 使用表中的连接和更新计算列值

ruby - Rails 查询太多?

java - 仅当特定对象具有可比较性时设置排序

data-structures - 无向图中的边数

php - 文本区域值未插入到 MYSQL 数据库中

c# - 列不是 PK 时的 EF6 MySQL StrongTypingException

jquery - 使用 jquery + Rails ujs 驱动程序 + google map v3 时 IE 8 jquery 错误。解决方法?

ruby-on-rails - SQLite3::ConstraintException:约束失败:

perl - 查找两个 Perl 嵌套哈希值之间的差异