2013-08-06 77 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) %>