Ruby中的这个递归循环有什么问题?

时间:2012-10-21 17:56:57

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord recursion

好的,我有这个循环

def page_children(page)
  content_tag :li do
    link_to page.url, "/#{page.url_path}/#{page.url}"
    if page.children.any?
      content_tag :ul do
        page_children(page)
      end
    end
  end
end

我不断获得stack level too deep

我使用这个gem作为我的树结构,我的模型和haml是以下

class Page < ActiveRecord::Base  
  acts_as_tree :order => 'sort_order'
  belongs_to :parent, :class_name => "Page" 
  scope :parent_nav, lambda{ |navigation| where(:parent_id => nil, :is_home => 0, :nav => navigation).order("sort_order") }
end

我的haml是以下

%ul
 - Page.parent_nav("Attend").each do |page|
 = page_children(page)

基本上我想要每个页面都有一个li,如果页面有子项,那么我想要所有孩子的另一个ul和li ...分机....但是我的循环不知何故...任何关于什么的想法我做错了

2 个答案:

答案 0 :(得分:4)

当您以递归方式调用时,您不会更改为page_children提供的参数。也许类似于以下内容(未经测试):

def page_children(page)
  content_tag :li do
    link_to page.url, "/#{page.url_path}/#{page.url}"
    page.children.each do |child|
      content_tag :ul do
        page_children(child)
      end
    end
  end
end

答案 1 :(得分:1)

我写(未经测试):

def render_pages(pages)
  return "" if pages.empty?
  content_tag(:ul) do
    pages.map do |page| 
      content_tag(:li) do
        link = link_to(page.url, helper_to_generate_the_page_path(page))
        link + render_pages(page.children)
      end
    end.join.html_safe
  end
end

= render_pages(Page.parent_nav("Attend"))