【发布时间】:2012-01-05 04:33:46
【问题描述】:
我有一个自联接模型:
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 来获取所有相关的 cmets,然后递归地渲染它们。
如何递归加载?
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
【问题讨论】:
-
不应该是
show_comments(child)吗? -
哦,是的,代码中可能有拼写错误,它只是为了呈现我想要的大致概念。
-
简单地说:你不能。我建议使用awesome_nested_set 或ancestry,它们都是解决此问题的不同实现(单个表上的深层嵌套结构)
标签: ruby-on-rails activerecord eager-loading