Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

acts_as_tree unordered list printout (See related posts)

In your view:
<ul>  
<% for category in @categories %>
    <li><%= link_to h(category.title), :action => 'edit', :id => category %>
        <%= find_all_subcategories(category) %>
   </li>
<% end %>
</ul>


Place this in a helper:
  def find_all_subcategories(category)
    if category.children.size > 0
      ret = '<ul>'
      category.children.each { |subcat| 
        if subcat.children.size > 0
          ret += '<li>'
          ret += link_to h(subcat.title), :action => 'edit', :id => subcat
          ret += find_all_subcategories(subcat)
          ret += '</li>'
        else
          ret += '<li>'
          ret += link_to h(subcat.title), :action => 'edit', :id => subcat 
          ret += '</li>'
        end
        }
      ret += '</ul>'
    end
  end

Comments on this post

lastobelus posts on Feb 13, 2006 at 18:08
Please don't take this personally, but doing something with the root and then calling a recursive function to do something with the children is a bad code smell, and will almost always need to be refactored to avoid duplication. You have the display of a node duplicated in two separate files. Always design your recursive functions to accept the root:

in view:
<%= list_all_activities(@activities) %>

in helper:
def list_all_activities(activities)
if activities.size > 0
ret = "<ul>\n"
activities.each { |subactivity|
ret += "<li>\n"
ret += link_to h(subactivity.name), :action => 'edit', :id => subactivity
ret += link_to "&nbsp;&nbsp;"+h("<add>"), :action =>'new', :id => subactivity
ret += "\n"
if subactivity.children.size > 0
ret += list_all_activities(subactivity.children)
end
ret += "</li>\n"
}
ret += "</ul>\n"
end
end


also, if you have to display in more than one format, you'd want to make a visitor pattern, with a visitor function on the model that you can pass a block to for marking up a line (or, separate blocks for branches / leaves)

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts