Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用mongoid和rails显示嵌套树的有效方法_Ruby On Rails_Mongodb_Tree_Mongoid - Fatal编程技术网

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

Ruby on rails 使用mongoid和rails显示嵌套树的有效方法,ruby-on-rails,mongodb,tree,mongoid,Ruby On Rails,Mongodb,Tree,Mongoid,我在文档中嵌套了一个注释树,使用mongoid递归地嵌入了许多注释,如下所示: Document: { ... comments: [{ ... updated_at, child_comments: [{ ... updated_at child_comments: [{...},{...}], ...},{...}] ...}] ...}] ..

我在文档中嵌套了一个注释树,使用mongoid递归地嵌入了许多注释,如下所示:

   Document: {
    ...
    comments: [{
      ...
      updated_at,
      child_comments: [{
        ...
        updated_at
        child_comments: [{...},{...}],
        ...},{...}]
      ...}]
    ...}]
   ...}
以一级“comment updated_at”属性排序的方式将其传递给视图的最有效方式是什么

当时,我在主文档模型中提出了以下内容:

  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
def展平注释
@平面注释=[]
self.comments.order_by([[:updated_at,:desc]])。每个人都有评论|
展平注释迭代器(注释)
结束
返回@flat_注释
结束
def展平注释迭代器(注释)

@flat_comments基本上有两种设计方法(其中一种与您的相同),它们都记录在上。这方面也有相似之处

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

提示:既然有,您可能想要实现的是一个图的一个部分