Categorising records (and then finding them by category)


have a look at ActiveRecord::Acts::NestedSet. It supports finding all
(indirect) children of a node. To realize the many-to-many relation
between items and categories I'd suggest introducing a new model
(something like 'Categorization'), which takes the role of an item in
your current design. Then every categorization can belong to one item,
and items have many categorizations.

Hope that helps, Tim

I have not used NestedSet in any of my projects yet. The only problem
I am aware of right now is, that inserting new nodes can be quite
expensive, since all nodes of the tree are numbered in a depth-first-
search manner.

But this might not be a problem, if the tree is only altered once in a
while (which could be the case in your scenario).

Maybe there are further drawbacks, that I am ignorant of.


no idea how to do it with 1 Query, and i'm really not yet really
comfortable with the whole Ruby lang itself,
but this could work with 2 queries if you use act_as_nested_set
instead of atcs_as_tree:

add this method to your model Category Model:

def direct_children_and_their_items
    self.class.base_class.find(:all, :conditions =>
"#{scope_condition} and #{parent_column} = #{}", :include =>

basically this is the direct_children() moethod of acts_as_nested_set,
but with ":include => :items" added.
then you can do:

#in your controller:
@cats_and_items =
# this would be 2 querys. 1 to find your category objects, one to find
all subcategories and their children

<% @cats_and_items.each do |c| %>
   <%= "<h1>#{Cateory}</h1>" %>
   c.items.each do |i|
      <%= "<li>#{}</li>"

no Idea if this really works, just an idea. maybe it helps.