Forum: Ruby on Rails Finding all "documents" belonging to a "category" using "act

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bc298d7a9345ed1f83b39afe288f5e9e?d=identicon&s=25 rob (Guest)
on 2007-07-03 16:38
(Received via mailing list)
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?
6c382202075fdcd2522d34633d7ecd9b?d=identicon&s=25 Dorren (Guest)
on 2007-07-03 18:00
(Received via mailing list)
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
This topic is locked and can not be replied to.