ruby-on-rails - 使用 mongoid 和 rails 显示嵌套树的有效方法

标签 ruby-on-rails mongodb tree mongoid

我在文档中嵌套了一个评论树,像这样使用 mongoid embeds_many_recursively:

   Document: {
    ...
    comments: [{
      ...
      updated_at,
      child_comments: [{
        ...
        updated_at
        child_comments: [{...},{...}],
        ...},{...}]
      ...}]
    ...}]
   ...}

以第一级“comment updated_at”属性排序的方式将其传递给 View 的最有效方法是什么?

目前我在主文档模型中想到了这个:

  def flatten_comments
    @flat_comments = []
    self.comments.order_by([[:updated_at, :desc]]).each do |comment|
      flatten_comments_iterator(comment)
    end
    return @flat_comments
  end

  def flatten_comments_iterator(comment)
    @flat_comments << comment
    comment.child_comments.each {|reply| flatten_comments_iterator(reply)}
  end

然后在 View 中遍历数组。

问题是: 1)在递归扁平化中,顺序在某处丢失了,我无法弄清楚在哪里,在纸上一步一步似乎按照需要的顺序添加项目,可能与类变量范围和访问有关。

2) 我不确定这是进行简单检索的最有效方法。

非常感谢您提供建议以及如何有效处理此类任务的经验。

最佳答案

基本上有 2 种设计方法(其中一种与您的相同),记录在 ruby driver's modeling examples 上.还有一个类似的question on SO关于它。

关于另一个问题:递归没有什么坏处,一般来说,如果注释没有很大的嵌套深度。但是,您的实现不是线程安全的,因为它使用实例变量,而不是局部变量。要处理它,您应该将 @flat_comments 转换为局部变量并将其作为参数传递给 flatten_comments_iterator 方法。

提示:因为任何 method recursion can be transformed to a iteration , 你可能想要实现的是 iterative preorder traversal的图表。

关于ruby-on-rails - 使用 mongoid 和 rails 显示嵌套树的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5934027/

相关文章:

ruby-on-rails - 根据品牌的主机名/域更改 Rails 3 应用程序的布局

jquery - 如何将路径助手与 jquery 单击事件一起使用?

python-3.x - export_graphviz extratreesclassifier python可视化

arrays - mongoDB:按内含值查找

mongodb - 为 $and 中给定查询的 mongodb 集合添加索引

jquery - CSS 溢出和无换行问题

c++ - 图问题 : Find whether two nodes share the same branch in O(1) time and O(1) storage per node

css - Ruby on Rails 中用户的个人 CSS 样式表

ruby-on-rails - 我无法在 Ruby on Rails 上提供静态图像

java - MongoDB 的唯一 int _id