Should I use iterations to display sub categories?

Hello,

I have a categories table that has an id and a category_id so that I can have a :belongs_to on itself.

On the left of my website I would like to display the main categories, then their sub categories below them.

I have read in the book I have that iterations may be a possibility.

I thought that perhaps there are other ways to do this such has having in my controller have two instance variables, one would have categories where category_id is null to display top categories, then the other variable would would have categories where category_id = a certain id.

Of course I just thought that the above mentioned might not work because what about if I added a top category, then I would have to hard code something each time - not desirable.

So what are your suggestions after readin my babble?

Joel Slowik wrote:

Hello,

I have a categories table that has an id and a category_id so that I can have a :belongs_to on itself.

On the left of my website I would like to display the main categories, then their sub categories below them.

I have read in the book I have that iterations may be a possibility.

so far, so good. that's the best way to do it

I thought that perhaps there are other ways to do this such has having in my controller have two instance variables, one would have categories where category_id is null to display top categories, then the other variable would would have categories where category_id = a certain id.

you would need more instance vars. one for each sub-category. since most likely you don't know in advance how many that would be...

Of course I just thought that the above mentioned might not work because what about if I added a top category, then I would have to hard code something each time - not desirable.

So what are your suggestions after readin my babble?

you first load all cats with category_id 0, then iterate over children and so on. if necessary, in a recursive function but it's more likely, that you'll know the deepness of nested cats, than their amount. still easier, than making guesses about the number of categories and needed variables

You might want to look at acts_as_tree (now a plugin) -- it does what you're asking.

With your current design you might consider this:

class Category < ARec:Base

has_many :subcategories, :class_name=>'Category', :foreign_key=>'category_id'   ... end

You'll gain some db efficiency since you can do your initial fetch as:

  @categories = Category.find(:all, :conditions=>{:category_id=>nil}, :include=>:subcategories)

That will fetch all the 'main' categories and their immediate subcategories.