我想显示一个由 gem 祖先管理的类别树。
我想使用一个助手,它会递归地遍历树并一个一个地返回类别,暂时没有 html 标签或内容。
module CategoriesHelper
def display_tree(category)
if category.has_children?
category.children.each do |sub_category|
display_tree(sub_category)
puts(sub_category.name) # to check if it goes here
end
end
category.name
end
end
category
参数是根类别之一。
它应该返回什么?
- 在网页中:
它仅显示根级别类别
Sport Beauty Automobile
- 在控制台中:
Men Indoor Women Children Water sport Garage
如果得到它们,则意味着递归有效,但没有。为什么它只返回第一次迭代?
我还想按以下顺序获取它们:
root/child/child-of-child
但是如果我想返回category.name
,它应该在最后一个位置。
你能给我你的意见吗?
PS:我刚刚发现(在添加标签期间)我一直在搜索中使用“递归”这个词,但它不存在,即使很多人在 stackOveflow 上使用它; o) -> “递归”,但我还是卡住了
** 编辑 **
现在我使用这段代码:
module CategoriesHelper
def display_tree(category)
tree = "<div class =\"nested_category\">#{category.name}"
if category.has_children?
category.children.each do |sub_category|
tree += "#{display_tree(sub_category)}"
end
end
tree += "</div>"
end
end
这给了我:
<div class ="nested_category">Sport
<div class ="nested_category">Men</div>
<div class ="nested_category">Women
<div class ="nested_category">Indoor</div>
</div>
<div class ="nested_category">Children</div>
<div class ="nested_category">Water sport</div>
</div>
<div class ="nested_category">Beauty</div>
<div class ="nested_category">Automobile
<div class ="nested_category">Garage</div>
</div>
但该 html 未被解释,并且相同的代码显示在显示的网页中。我的意思是我看到了
我可能漏掉了什么……也许是知识oO
谢谢
最佳答案
您使用的方法将仅返回一个值(实际上是对 category.name 的第一次调用) 关于控制台,您将获得循环内的 puts(这不是方法的返回值)。
试试这个,如果还有什么地方不够清楚请告诉我:
module CategoriesHelper
def display_tree(category)
tree = category.name
if category.has_children?
category.children.each do |sub_category|
tree += "/#{display_tree(sub_category)}"
end
end
tree
end
end
关于ruby-on-rails - 为什么我的 helper 递归方法不返回每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6074607/