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
  * Parent's sibling

There must be a better way...

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

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

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

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