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.

On Dec 28, 2:17 pm, Adam [email protected] wrote:

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).

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

On Dec 28, 2:49 pm, Bill K. [email protected] wrote:

Your migration might contain this (among other stuff):

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

Woops - that, of course, should have been:

t.column :parent_category_id, :integer

My bad.

-Bill

Great!!
Thanks for a quick answer!

On Dec 28, 2:49 pm, Bill K. [email protected] wrote:

And now you can theoretically do things like:

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

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

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

On 29 Gru, 06:44, “Jeffrey L. Taylor” [email protected]

Quoting A. [email protected]:

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