5

I have a self-joined model:

class Comment < ActiveRecord::Base
     belongs_to :parent, :class_name => 'Comment', :foreign_key => 'parent_id'
     has_many :children, :class_name => 'Comment', :foreign_key => "parent_id"
end

Later I wish to first make 1 sql call to grab all relevant comments, and then recursively render them.

How do I recursively eager load?

comments = Comment.where(:post_id => @post_id).includes(:comments=> [:comments => [:comments .... #How do I get this to recursively eager load?

def show_comments(comment)
   render comment
   comment.children.each do |child|
       show_comments(child)
   end
end
Razor Storm
  • 12,167
  • 20
  • 88
  • 148
  • Shouldn't it be `show_comments(child)`? – Finbarr Jan 05 '12 at 05:59
  • Oh yeah, there's probably typos in the code, it's just meant to present a general idea of what i want. – Razor Storm Jan 05 '12 at 08:08
  • simply put : you can't. I would advise using [awesome_nested_set](https://github.com/collectiveidea/awesome_nested_set) or [ancestry](https://github.com/stefankroes/ancestry) that are both different implementations addressing this problem (deeply nested structures on a single table) – m_x Apr 03 '13 at 09:08

1 Answers1

3

You could create a method that retrieves the deep nesting of IDs, load those, and rails will use it like a cache.

omarvelous
  • 2,774
  • 14
  • 18