Topic: acts_as_tree making to many db requests

I'm trying to find a better way to print the sidebar navigation on a site.

The current version (below) is hugely inefficient.

The output should be something like

* Ancestor-sibling 1
* Ancestor-sibling 2
* Ancestor
  * Parent
    * CURRENT PAGE
  * Parent's sibling


There must be a better way...


def navigation(current_page)
  root = Page.root
  recurse_navigation(current_page, root)
end

def recurse_navigation(selected_page, parent)
  ret = "\n<ul>\n"   
  parent.children.each do |child|
    ret += "\t<li>"
    css_class = 'selected' if child.id == selected_page.id
    ret << link_to(h(child.title), child.path, :class => css_class)

    if selected_page.ancestors.include?(child) or child.id == selected_page.id and child.children.size > 0
      ret << recurse_navigation(selected_page, child)
    end
    ret << "</li>\n"
  end
ret += "</ul>\n"
end

Re: acts_as_tree making to many db requests

See this post for a way to do this.

I don't know if it does completely what you want, but it may give you an idea on how to improve it. Feel free to ask more questions about it here.

Railscasts - Free Ruby on Rails Screencasts