递归生成树

代码
class  Product  <  ActiveRecord::Base
  acts_as_tree :order 
=>   " name "

  def self.roots 
    self.find(:all,:conditions 
=>  [ " parent_id=? " , 0 ]) 
  end
  
  def is_leaf
?  
    
return   ! self.has_children ?    
  end 
  
  def is_root
?  
    
return  self.parent_id  ==   0  
  end 
end

 

代码
module ProductsHelper
  def get_tree(trees) 
    tree_html 
=   ""
    trees.each 
do   | tree |  
      
#if  tree.is_root?
        tree_html 
+=   " <li><span><img src='../images/folder.gif' />#{tree.name}&nbsp;&nbsp;&nbsp;&nbsp;#{link_to('修改',edit_admin_product_path(tree.id))}</span> "
      #end

      
if   ! tree.children.empty ?  then
        tree_html 
+=   " <ul> "   +  get_tree(tree.children)  +   " </ul> "
      end
      tree_html 
+=   " </li> "
    end 
    
return  tree_html 
  end 
end

 

 

view中调用:

 

< ul id = " browser "   class = " filetree " >
<%=  get_tree(@products) %>
</ ul >

 

 

你可能感兴趣的:(递归)