2013-08-06 80 views
0

我是Ruby on Rails的新手,我需要使用嵌套評論來創建發佈/評論關係,就像作者可以相互回覆一樣。祖先,has_many_roots?

製造這樣的:

後/ comments.html:

<% @post.comments.roots.each do |c| %> 
    <%= nested_messages c.subtree.arrange(:order => :created_at) %> 
<% end %> 

這工作得很好,但顯然需要大量的查詢來渲染一棵樹,像N + 1,其中Ncomments.root.count

感謝您的幫助!

UPD: Soluton與.includes()對我的情況下,沒有工作,但我不是100%肯定,我是在做正確的事情都...

該解決方案爲我工作了很明顯 - 安排意見自理,通過指定POST_ID:

<%= nested_messages Comment.where('post_id = ?', @post.id).arrange(:order => :created_at) %> 

回答

0

您可以通過使用includes方法

希望這個作品對你的代碼

@post.comments.roots.includes(:subtree) 

我無法arrange幫助優化N + 1分的問題,因爲你沒有指定版本,正在處理

0

如果您的樹形結構如下所示:

Post 
    comment (root1) 
    comment (child11) 
    comment (child12) 
    comment(root2) 
    comment (child21) 
    comment (child22) 
... and so on 

可以更好地重塑結構這樣:

Post 
    comment (meta root, only one, which holder other comments 'roots' and we never render this comment in the view) 
    comment (child1) 
     comment (child11 
    comment (child2) 
     comment (child21) 
    comment (child3) 
    ... and so on 

現在將被執行2的查詢,而不是N + 1

0

Soluton與.includes()(或3')沒有爲我的案件工作,但我不是100%確定我正在做所有事情...

解決方案爲我工作是非常明顯的 - 安排評論themself,通過指定post_id:

<%= nested_messages Comment.where('post_id = ?', @post.id).arrange(:order => :created_at) %>