How to do downloadable loading on descendants of a model using Rails and Ancestry

I'm currently working on a block application that has article / comment models linked through has_many / belongs_to associations. To create the functionality of nested comments, I use a pedigree. However, I would like to get a full load on all descendants of the comment. Any ideas on how to approach this? I tried to use join and where, but it looks like they produce n + 1 queries. This is how I call the method to display them in the view.

<%= nested_comments_display comments.arrange(:order => :created_at) %>

And here is the nested_comments_display method

def nested_comments_display(comments)
  comments.map do |comment, sub_comments|
    render(comment) + content_tag(:div,nested_comments_display(sub_comments), 
                                :class => "nested_comment")
  end.join.html_safe
end

I also use the gem of dignity, and my comment The controller looks like

class CommentsController < ApplicationController

  expose(:article)
  expose(:comments, ancestor: :article) 
  expose(:comment, attributes: :comment_params)

  ....
end
+4
1

( ) - , , ...

class CachedAncestryCollection
  def initialize(collection)
    @collection = collection.to_a
  end

  def children_for(parent_id = nil)
    @collection.select do |node|
     parent_id ? (node.ancestry && node.ancestry.match(/#{parent_id}$/)) : node.ancestry.nil?
    end
  end
end

# ...

preloaded_subtree = Comment.where(:id => comments.map(&:subtree_ids))
cached = CachedAncestryCollection.new(preloaded_subtree)

def nested_comments_display(cached, parent_id = nil)
  content_tag(:div) do
    cached.children_for(parent_id).map do |child|
      nested_comments_display(cached, child.id)
    end
  end
end
+2

All Articles