rob
2007-Jul-03 14:37 UTC
Finding all "documents" belonging to a "category" using "acts_as_tree"
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? --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
Dorren
2007-Jul-03 15:59 UTC
Re: Finding all "documents" belonging to a "category" using "acts_as_tree"
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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---