0

我有以下类别模型:

class Category
    include Mongoid::Document
    include Mongoid::Tree

    field :title, type: String
    validates :title, presence: true, uniqueness: true, length: {minimum: 2}
end

我存储了以下测试数据:

Root 1
    Leaf 1
        Subleaf 1
    Leaf 2
Root 2
    Leaf 3

现在当我调用 Category.all 它返回:

Root 1
Leaf 2
Leaf 1
Root 2
Subleaf 1
Leaf 3

但我需要以下订购:

Root 1
Leaf 1
Subleaf 1
Leaf 2
Root 2
Leaf 3
4

1 回答 1

1

Mongoid::Tree默认情况下不排序树。相反,它包括一个用于订购的模块。只需将其包含在您的课程中:

class Category
  include Mongoid::Document
  include Mongoid::Tree
  include Mongoid::Tree::Ordering

  field :title, type: String
  validates :title, presence: true, uniqueness: true, length: {minimum: 2}
end

那应该已经解决了您的问题。如果没有,请查看Mongoid::Tree::Traversal. Mongoid::Tree这将为您提供一种Category#traverse方法,使您可以在呼吸优先或深度优先(我猜这就是您想要的)遍历之间进行选择。

有关排序和遍历的更多文档,请参阅http://benediktdeicke.com/mongoid-tree/#Orderinghttp://benediktdeicke.com/mongoid-tree/#Traversal

于 2012-10-16T06:52:29.863 回答