0

好吧,我正在使用Awesome嵌套集在轨道上使用嵌套评论系统。我目前正在实现一个递归函数来使嵌套工作(我知道这对于性能来说非常低效,但我只是希望在调整性能之前就能够工作)。帮助方法范围问题的递归函数

在我的应用程序控制器

所以我有这样的事情(建筑HTML):

def create_comments_list(comment, commentlist) 
    commentlist += "<div class=\"comment\" style=\"padding-left:20px;\"><div style=\"display:none;\" class=\"parent_id\">#{comment.id}</div>#{comment.user.name}:<br/><div class=\"ccontent\">#{comment.content}</div><br/><a href=\"#reply\" class=\"reply\" style=\"color:black;\">Reply</a>"; 
    children = comment.children 
    children.each do |c| 
    create_comments_list(c, commentlist) 
    end 
    commentlist += "</div><div class=\"shortdivider\">&nbsp;</div>" 
    commentlist 
end 

我在控制器调用这样的:

@commentlist = create_comments_list(c, @commentlist) 

这似乎是拼尽了全力递归...然而,在1条家长评论和1条儿童评论的情况下,评论列表只会吐出家长评论。如果我记录的东西,我可以看到,孩子确实被追加到递归调用中的@commentlist,但是当它展开到父节点进入递归的地方时,commentlist变量不再包含子节点。看来我不明白这些变量的范围......我需要评论列表在内部递归调用解除后保留它的值。任何人都可以摆脱一些光? (或者一些更好的方法来做这件事吗?我的坏风格响铃正在我头上)

回答

2

如果你想改变你的commentslist参数,使用铲运营商<<而不是+=

+=创建一个新的字符串对象并将其分配给您的变量,但堆栈中的函数仍旧引用旧的字符串值。 <<更改现有的字符串对象。

a = "foo" # => "foo" 
a.object_id # => 69847780 
a += "bar" # => "foobar" 
a.object_id # => 69786550 (note this is not the same object as before) 

b = "foo" # => "foo" 
b.object_id # => 69764530 
b << "bar" # => "foobar" 
b.object_id # => 69764530 
+0

谢谢你的 – Msencenb