【问题标题】:self-join eager loading recursively?递归自加入急切加载?
【发布时间】: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_setancestry,它们都是解决此问题的不同实现(单个表上的深层嵌套结构)

标签: ruby-on-rails activerecord eager-loading


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    相关资源
    最近更新 更多