Many to Many Category structure with itself

Basically, I’m trying to have a table called “categories” have a many to
many relationship with itself. But I also want each catagory to be able
to be “copied” into another category so it is essentially a child
category to more than one parent. To me the obvious way of doing this is
by creating another table called category_maps (and a model called
CategoryMap). The category_maps table would keep the parent_id/child_id
relationships for the categories table.
As far as the user experience, I want it to work so if you go to
controllername/list_cats (with no id) it will display all cats with a
parent_id of 0. If they go to controllername/list_cats/3 it should
display all cats with a parent_id of 3
My problem is that when I try to implement this concept in the actuall
code, I run into problem after problem so I must be missing something.
If anyone can help or at least send me to an OS app that has the code I
need, I would greatly appreciate it.

Kyle wrote:

Basically, I’m trying to have a table called “categories” have a many to
many relationship with itself. But I also want each catagory to be able
to be “copied” into another category so it is essentially a child
category to more than one parent. To me the obvious way of doing this is
by creating another table called category_maps (and a model called
CategoryMap). The category_maps table would keep the parent_id/child_id
relationships for the categories table.
As far as the user experience, I want it to work so if you go to
controllername/list_cats (with no id) it will display all cats with a
parent_id of 0. If they go to controllername/list_cats/3 it should
display all cats with a parent_id of 3
My problem is that when I try to implement this concept in the actuall
code, I run into problem after problem so I must be missing something.
If anyone can help or at least send me to an OS app that has the code I
need, I would greatly appreciate it.

You can do what you describe using a self-referential
has_and_belongs_to_many association. Check on the Rails wiki for some
examples. You should be able to do this with a has_many :through, but
there’s a bug that prevents it from working (which I’m trying to get
fixed).


Josh S.
http://blog.hasmanythrough.com

Also see acts_as_tree it might be better.

Kris wrote:

Also see acts_as_tree it might be better.

I worked everything out. the acts_as_tree method is very helpfull. Thank
you

Kyle wrote:

Kris wrote:

Also see acts_as_tree it might be better.

I worked everything out. the acts_as_tree method is very helpfull. Thank
you

I got the self-ref has_many :through worked out:

http://blog.hasmanythrough.com/articles/2006/04/21/self-referential-through


Josh S.
http://blog.hasmanythrough.com