1

我使用 gemancestry来创建评论。

现在,我可以列出所有评论。

但我想将序列号推送到每条评论。

例如,如果有 3 条评论,则第一个评论标注 1,下一条标注标注 2,..

我不知道该怎么做?

显示.html.haml

- if notice
  %p.alert.alert-success= notice
= nested_comments(@comment.subtree.arrange(:order => :created_at))

帮手

  def nested_comments(comments)
    if comments.respond_to? :map
      comments.map do |comment, sub_comments|
        render(comment) + content_tag(:div, nested_comments(sub_comments), :class => "nested_comments")
      end.join.html_safe
    end
  end

each_with_index 不适用于递归

如果我有 4 条评论,我想为每条评论显示 0,1,2,3

但是 each_with_index 不能成功,因为它是一个递归调用。

comments.each_with_index.map do |(comment, sub_comments), i|

注释

=> {#<Comment id: 2, user_id: 1, ip: nil, content: "I'm id2 the second floor VIVOTEK Releases New Vers...", commentable_id: nil, commentable_type: nil, created_at: "2014-11-07 03:59:38", updated_at: "2014-11-07 06:56:12", ancestry: nil>=>
  {#<Comment id: 4, user_id: 1, ip: nil, content: "lala", commentable_id: nil, commentable_type: nil, created_at: "2014-11-07 05:22:41", updated_at: "2014-11-07 05:22:41", ancestry: "2">=>
    {#<Comment id: 5, user_id: 1, ip: nil, content: "son of 4", commentable_id: nil, commentable_type: nil, created_at: "2014-11-07 06:38:04", updated_at: "2014-11-07 06:38:04", ancestry: "2/4">=>
      {},
     #<Comment id: 6, user_id: 1, ip: nil, content: "dild last 252", commentable_id: nil, commentable_type: nil, created_at: "2014-11-07 06:52:15", updated_at: "2014-11-07 06:52:15", ancestry: "2/4">=>
      {}}}}
4

3 回答 3

0

我不知道一个优雅的解决方案。但是您可以将一个计数器传递给您的nested_comments函数,并手动处理问题——这很可能意味着map根本没有。丑陋,我知道。

举一个更简单的例子,你是否需要一个:

def nested_foo(result, string, index)
  index += 1
  result << "\n#{index}: #{string}"

  if index >= 10
    return result
  else
    return nested_foo(result, string, index)
  end

end
于 2014-11-07T09:06:33.610 回答
0

ruby 中的每个可枚举实例都有一个方法each_with_index,提供an_enumerator. 所以在你的情况下,我建议使用:

- comments.map do |comment, sub_comments|
+ comments.each_with_index.map do |idx, comment, sub_comments|

希望能帮助到你。

于 2014-11-07T07:33:29.033 回答
0

您可以with_index与地图一起使用

comments.map.with_index do |comment, sub_comments, index|
于 2014-11-07T07:38:50.313 回答