Forum: Ruby on Rails Parent listing children.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
693d60c75576b61249b9ede5b0a3d0b2?d=identicon&s=25 Adrian (Guest)
on 2006-06-03 23:58
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!
13ea48f056b19349027d2f4a6921a46a?d=identicon&s=25 Jean-François (Guest)
on 2006-06-04 00:35
(Received via mailing list)
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.
693d60c75576b61249b9ede5b0a3d0b2?d=identicon&s=25 Adrian (Guest)
on 2006-06-04 01:11
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!
This topic is locked and can not be replied to.