我希望通过在1..5循环中使用@comment1@comment2更改为i我有以下代码是相当重复的我希望把它弄干。
嗨,我正在使用acts_as_commentable_with_threading。我基本上是循环浏览所有评论,并检查该评论是否有孩子如果是,请打印出孩子,同时检查这些孩子是否有孩子。所以我打算深入一些层次,因此,@comment1,2,3等等……我怎么能把它弄干呢递归怎么办如果没有,我可以深入一些层次,例如在@comment5结束注释缩进。
编辑!
谢谢你,萨米隆!
这是更新的helper函数。。。

    def show_comments_with_children(comments)

     comments.each do |comment|

         yield comment
         if comment.children.any?
           concat <<-EOF.html_safe
                <div class="span7 offset1-1 pcomment">
           EOF
            show_comments_with_children(comment.children) {                 |x| yield  x } #Dont worry, this will not run another query :)
               concat <<-EOF.html_safe
                    </div>
               EOF
         end
     end
  end

<div class="span7 offset1-1 pcomment">
<% @comment1 = comment.children%>
<% for comment in @comment1 %>
 <%= render "comment_replies", :comment => comment %>

<div class="span7 offset1-1 pcomment">
<% @comment2 = comment.children%>
<% for comment in @comment2 %>
<%= render "comment_replies", :comment => comment %>

<div class="span7 offset1-1 pcomment">
<% @comment3 = comment.children%>
<% for comment in @comment3 %>
<%= render "comment_replies", :comment => comment %>

                <% end %>
            </div>

……
<%(1..5).each do |i| %>
  <% @comment1 = comment.children%>
  <% for comment in @comment1 %>
    <%= render "comment_replies", :comment => comment %>
  <% end %>
<% end %>

最佳答案

可能你在找instance_variable_set

# Following snippet is not TESTED. It is here to just demonstrate "instance_variable_set"
<%(1..5).each do |i| %>
  <% instance_variable_set("@comment#{i}", comment.children) %>
  <% for comment in instance_variable_get("@comment#{i}") %>
    <%= render "comment_replies", :comment => comment %>
  <% end %>
<% end %>

但这绝对不是一个值得推荐的方法。你可以分享你的控制器代码和你想在你的视图中实现的东西一定有办法把它弄干在你的职位上你总是得到comment.children真的吗?
实际解决方案:
您的视图代码将如下所示
#0th level is the top level
<% show_comments_with_children(@comments, 0) do |comment, level|%>
   <!-- #Use level to differ the design for different depth-->
   <%= render "comment_replies", :comment => comment %>
<%end%>

并在helper函数中添加这个helper函数show_comments_with_children。会的。
def show_comments_with_children(comments, level)
   comments.each do |comment|
       yield comment, level
       if comment.children.any?
           show_comments_with_children(comment.children, level+1) {|x, l| yield x, l} #Dont worry, this will not run another query :)
       end
   end
end

10-06 01:28