Parent listing children


#1

My database is set up as Categories > Things associated by category_id
and has_many and belongs_to.

How would I go about listing all the categories and under each Category
is it’s children? Is there an easy rails way to do this - preferably
without using acts as tree? Any help is appreciated - thanks!


#2

Hello Adrian,

My database is set up as Categories > Things associated by
category_id and has_many and belongs_to.

How would I go about listing all the categories and under each
Category is it’s children? Is there an easy rails way to do this -
preferably
without using acts as tree? Any help is appreciated - thanks!

Can you describe your models and what you want to achieve
more clearly ?

From what I understand, you’ve got Category has_many :things
and Thing belongs_to :category .

So you can retrieve your categories and preload their children
with :

@categories = Category.find :all, :include => :things

in the view, iterate on categories and each time, use category.things

Or when you’re speaking of acts_as_tree, do you imply
that Category is a self-referencing model (has_many :subcategories,
:class_name => ‘Category’, :foreign_key => ‘parent_id’ …) ?
and you want to display subcategories ?

РJean-Fran̤ois.


#3

Basically I have two tables, Categories and Things with the model
explained above I need it to view such as

+Category1
-Thing1
-Thing2
+Category2
-Thing#
-Thing#etc.

The only way i see it being done is having a for loop displaying
categories and then another for loop within that displaying the things
in reference to the category. I was curious if there was a rails way to
do this as there seems to be alot that I’m missing and I would also have
to call SQL within the view which would go against MVC abit.

Using your suggestion that actually sounds good as far I know - how
would i go about implementing grouped by to make it work?

Thanks for your reply!