# Category - Subcategory

**URL:** <https://www.ruby-forum.com/t/category-subcategory/114140>\
**Category:** Rails\
**Created:** [September 8, 2007, 12:55pm UTC](https://www.ruby-forum.com/t/category-subcategory/114140 "2007-09-08T12:55:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Paul\_Baylis](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ecc23a/32.png) [@Paul\_Baylis](https://www.ruby-forum.com/u/Paul_Baylis)\
**Post date:** [September 8, 2007, 12:55pm UTC](https://www.ruby-forum.com/t/category-subcategory/114140/1 "2007-09-08T12:55:47Z")

</div>

Hi there,

I have a Products table. Each product has a category\_id and  
subcategory\_id which relate to the categories and subcategories tables  
respectively.

1. How do I create a view for creating new subcategories? Obviously,  
upon entering a new subcategory, I would need to select the category  
to which it should belong.

2. Same problem with entering new products. I have to choose a  
category from a drop-down list and then a subcategory that relates to  
that category.

Any help greatly appreciated.

God bless,  
Paul

---

<div class="post-metadata">

**Author:** ![Paul\_Baylis](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ecc23a/32.png) [@Paul\_Baylis](https://www.ruby-forum.com/u/Paul_Baylis)\
**Post date:** [September 8, 2007, 4:07pm UTC](https://www.ruby-forum.com/t/category-subcategory/114140/2 "2007-09-08T16:07:09Z")

</div>

Hey,

I personally favor having a ‘tree-like’ category structure instead of  
separate categories/subcategories. When you think about it, a  
‘Category’ and a ‘SubCategory’ are normally the same thing - just one  
is a parent of the other.

Try looking at ‘acts\_as\_tree’ for your categories. In this set up,  
each category can have a parent\_id which tells you which category a  
sub or ‘child’ category is in.

For example:

## id name parent\_id

1 Books 0  
2 Fiction 1  
3 Non-Fiction 1

You might want to assign a book to non-fiction so the book’s  
category\_id becomes ‘3’. For simple category systems, I tend to use a  
select box like this:

Books  
Fiction  
Non-fiction

As for managing the categories, I tend to have the child categories  
listed on my ‘Edit Category’ form. From there I can edit and create  
new child categories.

Hope that helps,

Steve

[http://www.stephenbartholomew.co.uk](http://www.stephenbartholomew.co.uk)

---

<div class="post-metadata">

**Author:** ![Paul\_Baylis](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ecc23a/32.png) [@Paul\_Baylis](https://www.ruby-forum.com/u/Paul_Baylis)\
**Post date:** [September 8, 2007, 4:47pm UTC](https://www.ruby-forum.com/t/category-subcategory/114140/3 "2007-09-08T16:47:13Z")

</div>

Hi Steve,

Thanks for the advice. I like the tree idea and your idea for the drop-  
down menu. Would you have the templates to view so I can see more  
construction detail?

Much appreciated if so.

God bless,  
Paul
