# Building a directory tree into the database

**URL:** <https://www.ruby-forum.com/t/building-a-directory-tree-into-the-database/160209>\
**Category:** Rails\
**Created:** [February 12, 2009, 11:58pm UTC](https://www.ruby-forum.com/t/building-a-directory-tree-into-the-database/160209 "2009-02-12T23:58:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![elioncho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/ed8c4c/32.png) [@elioncho](https://www.ruby-forum.com/u/elioncho)\
**Post date:** [February 12, 2009, 11:58pm UTC](https://www.ruby-forum.com/t/building-a-directory-tree-into-the-database/160209/1 "2009-02-12T23:58:47Z")

</div>

Hello,

Does anyone can give me some pointers on building a directory tree. I  
want to map a directory of folders and files into a database. I am not  
sure how to do this dynamically. I think acts\_as\_tree could help me do  
this. Any ideas?

Thanks,

Elias

---

<div class="post-metadata">

**Author:** ![elioncho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/ed8c4c/32.png) [@elioncho](https://www.ruby-forum.com/u/elioncho)\
**Post date:** [February 13, 2009, 11:29am UTC](https://www.ruby-forum.com/t/building-a-directory-tree-into-the-database/160209/2 "2009-02-13T11:29:20Z")

</div>

Hello,  
I manage a database to map directories too …  
I use the plugin better\_nested\_set :  
[http://wiki.rubyonrails.org/rails/pages/BetterNestedSet](http://wiki.rubyonrails.org/rails/pages/BetterNestedSet)  
You can mange roots and children easily with this.  
When you get, for example, a directory containing others directories  
and files,  
you can add the first directory as root and subdirectories and files  
as children of root… with “child.move\_to\_child\_of root”  
When you want to get children for the root directory with your model :  
“root.children” or “child.children” etc …  
And to get the parent directory : “chid.parent” or “child.ancestors”  
etc …  
You just have to parse the directory tree with Dir.entries or anything  
else and add the results to the database using your model containing  
acts\_as\_nested\_set and saving each entries using move\_to\_child\_of  
method if it’s needed.
