# Finding all "documents" belonging to a "category" using "act

**URL:** <https://www.ruby-forum.com/t/finding-all-documents-belonging-to-a-category-using-act/108446>\
**Category:** Rails\
**Created:** [July 3, 2007, 4:38pm UTC](https://www.ruby-forum.com/t/finding-all-documents-belonging-to-a-category-using-act/108446 "2007-07-03T16:38:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/838e76/32.png) [@rob](https://www.ruby-forum.com/u/rob)\
**Post date:** [July 3, 2007, 4:38pm UTC](https://www.ruby-forum.com/t/finding-all-documents-belonging-to-a-category-using-act/108446/1 "2007-07-03T16:38:44Z")

</div>

I have a “categories” table built using acts\_as\_tree and a “documents”  
table that belongs to a specific category. Each category is a child of  
a “root” category and I’d like to get _all_ of the documents belonging  
to the categories of a root category. Here’s what the structure looks  
like:

Root 1  
Category 1 # contains documents  
Category 2 # contains documents  
Root 2  
Category 3 # contains documents  
Category 4 # contains documents

categories\_table:

# using acts\_as\_tree

# has\_many :documents

id,  
parent\_id,  
name

documents\_table:

# belongs\_to :category

id,  
category\_id,  
name

I know to get the documents for a specific category I can just do  
category.documents. But I’d like to find all of the documents if I  
visit ‘Root 1’ or ‘Root 2’ which means it’ll find the documents  
belonging to the categories in Root 1 that belong to Root 1.

Can someone help?

---

<div class="post-metadata">

**Author:** ![rob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/838e76/32.png) [@rob](https://www.ruby-forum.com/u/rob)\
**Post date:** [July 3, 2007, 6:00pm UTC](https://www.ruby-forum.com/t/finding-all-documents-belonging-to-a-category-using-act/108446/2 "2007-07-03T18:00:54Z")

</div>

use acts\_as\_nested\_set  
see /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active\_record/  
acts/nested\_set.rb for more info

Dorren

============ category.rb ===================  
class Category \< ActiveRecord::Base  
acts\_as\_nested\_set

has\_many :documents,  
:foreign\_key =\> “category\_id”

validates\_presence\_of :name  
end

======= migration: create\_cateogries.rb ============  
class CreateCategories \< ActiveRecord::Migration  
def self.up  
create\_table :categories do |t|  
t.column :name, :string  
t.column :parent\_id, :integer, :default =\> 0  
t.column :lft, :integer, :default =\> 0  
t.column :rgt, :integer, :default =\> 1  
end  
[:parent\_id, :lft, :rgt].each{|x|  
add\_index :categories, x  
}  
end

def self.down  
[:parent\_id, :lft, :rgt].each{|x|  
remove\_index :categories, x  
}  
drop\_table :categories  
end  
end
