【发布时间】:2011-08-29 19:08:24
【问题描述】:
我想显示一个由 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,它应该在最后一个位置。
你能给我你的cmets吗?
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
谢谢
【问题讨论】:
-
请添加您用于在模板上呈现它的视图代码。您可能缺少包含 display_tree() 方法的 raw() 方法,以防止 Rails >= 3 自动转义 html。
标签: ruby-on-rails ruby methods recursion helper