递归自加入急切加载?

Raz*_*orm 5 activerecord ruby-on-rails eager-loading

我有一个自我加入的模型:

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
Run Code Online (Sandbox Code Playgroud)

后来我希望首先进行1次SQL调用以获取所有相关注释,然后递归渲染它们.

我如何递归加载?

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
Run Code Online (Sandbox Code Playgroud)

oma*_*ous 3

您可以创建一个方法来检索 ID 的深层嵌套,加载它们,rails 将像缓存一样使用它。