Forum: Ruby on Rails best way to design uknown depth of subcategories

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.
Adam D. (Guest)
on 2005-12-24 05:59
(Received via mailing list)
Hello,

 What would be the best way to design a table of posts that belong to a
unknown depth of categories.  Say i wanted to display the posts of data
(i.e.,
craigslist) but the category could be something like
NewYork/RealEstate/Housing/ForSale/ByOwner.  Would acts_as_tree work
best
here and assign each sublevel to a different id?  just trying to take
the
easiest approach here using the best tools.  Also an easy way to display
the
category should be easy to accomplish as well with this model.

thanks
adam
Jon Olson (Guest)
on 2005-12-24 11:23
(Received via mailing list)
To me this sounds like something acts_as_tree is ideal for. Perhaps
something like:

class Category < AR::Base
	acts_as_tree
	has_many :posts
end

class Post < AR::Base
	belongs_to :category
end

As for display... It all depends on what sort if UI you're looking
for. You could easily flatten the category list and use a select box
to pick what a post belongs to. Alternatively you could display it as
a tree with links for each category which update either a visible or
hidden select via JavaScript. To do this you'd simply select
Categories with no parent and descend in a depth first manner (so
your constructed set of links looks like a proper tree rather than
jumping all over). Your links could be something along the lines of
(although ideally prettier):

<% onchange = "$('hiddenFieldId').value = #{cat.id}" %>
<%= link_to "#", cat.name, :onChange => onchange %>

Perhaps with some appropriate styling and classes applied to each
level of links to provide that tree-like depth (nested divs with a
padding-left style attribute would probably work nicely). Hope this
helps.

-- Jon
This topic is locked and can not be replied to.