递归自加入急切加载?

时间:2012-01-05 04:33:46

标签: ruby-on-rails activerecord 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

稍后我希望首先进行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

1 个答案:

答案 0 :(得分:3)

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