Mongoid ::树排序

时间:2012-10-15 15:10:37

标签: ruby mongodb mongoid

我有以下分类模型:

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

1 个答案:

答案 0 :(得分: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