2012-01-05 12 views
5

私は自己入社モデルを持っている:self-join 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 
+0

'show_comments(child)'にするべきではありませんか? – Finbarr

+0

ああ、おそらくコード内に誤字があります。それは単に私が望むものの一般的な考え方を提示することを意味しています。 –

+0

単純に言えば:できません。この問題に対処する異なる実装である[awesome_nested_set](https://github.com/collectiveidea/awesome_nested_set)または[ancestry](https://github.com/stefankroes/ancestry)を使用することをお勧めします。単一のテーブル) –

答えて

3

IDのディープネストを取得し、それらをロードし、レールがキャッシュのように使用するメソッドを作成できます。

関連する問題