---
title: "ExtJS tree in rails"
author: "无明"
date: "2007-05-03T22:19:29Z"
tags: []
slug: "extjs-tree-in-rails"
draft: false
lastmod: "2007-05-03T22:19:29Z"
id: 76860
url: "https://javaite.iteye.com/blog/76860"
---

今天发现ExtJS支持Prototype了(不喜欢在rails中混用prototype和yui)，赶紧去下载一个,并试验了一下tree组件，感觉还不错，考虑以后就用ExtJS了。
闲话不说了，贴代码
schema.rb


```ruby

ActiveRecord::Schema.define() do

  create_table "categories", :force => true do |t|
    t.column "id", :int
    t.column "parent_id", :int
    t.column "tree_id",   :int
    t.column "lft",       :int
    t.column "rgt",       :int
    
    t.column "name",      :string 
    t.column "description", :string
    
    t.column "created_at",:int
       
  end
   
   add_index :categories, :name, :unique  => true
    

end


```


接着是model:

```ruby

class Category < ActiveRecord::Base
  acts_as_nested_set :scope => :tree_id
  
  def leaf?
    if self.rgt - self.lft == 1
      return true
    else
      return false
    end 
  end

end


```

这里用的是Nested_set存储树，所以只需计算节点的左右值是否连续来判断叶子节点。Nested_set查询比较好用，就是插入效率差，用于目录的存储比较合适，一般目录不会频繁更新。

然后是rhtml：

```ruby

<html>
    <head>
        <title>r</title>

        <%= stylesheet_link_tag "../javascripts/ext/resources/css/ext-all.css" %>
        <%= javascript_include_tag "ext/adapter/prototype/prototype.js" %>
        <%= javascript_include_tag "ext/adapter/prototype/scriptaculous.js" %>
        <%= javascript_include_tag "ext/adapter/prototype/effects.js" %>
        <%= javascript_include_tag "ext/adapter/prototype/ext-prototype-adapter.js" %>
        <%= javascript_include_tag "ext/ext-all-debug.js" %>

    </head>	
    <body>	
       <%= javascript_include_tag "category_tree.js" %>
       <div id="tree-div" style="border:5px solid #99bbe8; overflow:hidden; width:130px;"></div>
   
    </body>
</html>

```

让页面加载时同时加载树组件，也就是那个category_tree.js：


```

Ext.onReady(function(){
    // shorthand
    var Tree = Ext.tree;
    
    var tree = new Tree.TreePanel('tree-div', {
        animate:true, 
        loader: new Tree.TreeLoader({dataUrl:'http://localhost:3000/admin/category/category_tree'}), //修改这里
        enableDD:true,
        containerScroll: true
    });

    // set the root node
    var root = new Tree.AsyncTreeNode({
        text: 'Ext JS',
        draggable:false,
        id:'source'
    });
    tree.setRootNode(root);


    // render the tree
    tree.render();
    root.expand();
});

```

这个是抄ExtJS的Demo，只是改了数据源。ExtJS需要接收JSON格式的数据，我们可以在actioncontroller中提供：

```ruby

class Admin::CategoryController < ApplicationController

  def category_tree
    
    categories = Category.find_by_sql("select * from categories where parent_id is null") 
    
    data = get_tree(categories,nil)  
   
    render :text=>data.to_json, :layout=>false
    
  end 
  
  def get_tree(categories, parent)
     data = Array.new
     
     categories.each { |category|
       if !category.leaf?
         
         if data.empty?
           data =   [{"text"  =>  category.name,"id"  => category.id,"cls" => "folder" ,"leaf"  => false,
             "children" => get_tree(category.children,category) }] 
         else
           data.concat ([{"text"  =>  category.name,"id"  => category.id,"cls" => "folder" ,"leaf"  => false,
              "children" => get_tree(category.children,category)}])
        end
        
       else
         data.concat([{"text" => category.name,"id" => category.id,"cls" => "file","leaf" => true}]) 
       end
         
     }
     return data
     
  end
 
end


```

这段代码使用递归构造了一棵树，并转换成ExtJS需要的json数据返回页面。
好啦，这时用浏览器访问就能看到效果了.只是写了一点点代码，加上ExtJS，我们就有一个树型目录了，想起以前用java+xloadtree做树型目录的那个费劲啊，哎