Efficient way to display a nested tree with mangoids and rails

I have a comment tree nested in a document using mongoid embeds_many_recursively as follows:

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

What is the most efficient way to convey it in a way that is ordered by the comment comment_1 attribute? first level?

At the moment, I came up with this inside the main document model:

  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

and then just repeated in the view above the array.

Problems: 1) in recursive smoothing, the order is lost somewhere, and I can’t understand where, step by step, on paper, it seems that the elements are added in the right order, maybe something is related to the scope of the variable and access.

2) I'm not sure if this is the most efficient way to do a simple search.

, .

+3
1

( , ), ruby ​​. SO .

: , , . , , . , @flat_comments flatten_comments_iterator.

. , .

+2

All Articles