Belongs_to herself

Hi!
I have a problem with belongs_to and has_many, the thing is
i have a category table which points to herself if it's a subcategory
of another category.

I just started using ruby on rails, and don't know how to implement
that or if it can be done (I assume it can).

Thank for any help.

You assume correctly. Here's an example:

class Category < ActiveRecord::base
  belongs_to :parent_category, :class_name => 'Category', :foreign_key
=> 'parent_category_id'
  has_many :subcategories, :class_name => 'Category', :foreign_key =>
'parent_category_id'
end

Your migration might contain this (among other stuff):

create_table :categories do |t|
  t.column :parent_category, :integer
end

And now you can theoretically do things like:

subs = Category.find(1).subcategories
parent = Category.find(2).parent

-Bill

Woops - that, of course, should have been:

t.column :parent_category_id, :integer

My bad.

-Bill

And this should have been:

parent = Category.find(2).parent_category

Sorry for the extra messages. I wasn't being as careful and thorough
as I should have been.

-Bill

Great!!
Thanks for a quick answer!

Quoting Adam <anlauf.adam@gmail.com>:

Hi!
I have a problem with belongs_to and has_many, the thing is
i have a category table which points to herself if it's a subcategory
of another category.

I just started using ruby on rails, and don't know how to implement
that or if it can be done (I assume it can).

Look at acts_as_tree. It's a plugin in Rails 2.0, builtin in Rails 1.2.

Example:

class Task < ActiveRecord::Base
  has_many :comments, :dependent=>:destroy
end

class Comment < ActiveRecord::Base
  belongs_to :task
  acts_as_tree :order=>'created_at'
end

Tasks have a hierarchy of comments with replies and replies can have replies
arbitrarily deep.

task = Task.find(id)
task.comments # top level comments
task.comments[0].comments # replies to first top level comment

comment is like a category, reply is like a sub-category.

HTH,
  Jeffrey

OK, thanks!!
I'll look that up too.