Geeks With Blogs
Matt Roberts Rails and .NET

Rails makes such a nice change from coding in .NET. I mean, I do like .NET and C#, but sometimes its very bloated and can be quite cumbersome to do things.

Rails, on the other hand, isn't big. Or cumbersome. In fact, its downright lean and to-the-point, unlike my blog posts (what there are of them!).

Anyway, today we're talking category trees, surely one of the most exciting concepts that there is to talk about. One thing that made me smile recently was the need to list all the categories that a company was tagged to. So, this happens with code that looks like this :-

<%for cat in @Categories %>
    <%= + "<br>" %>
<% end %>

.. Where @Categories is a collection of categories from the controller, and is generated like this:

@Categories = Company.find(params["id"]).Category.find(:all)

So, this noddy code just lists all cats that the company was tagged to. After deploying this, I was asked to change it so that the full hierarchy of categories was displayed. So instead of "Cat 1", the user wants to see "Root -> Services -> Cat 1". Hmmm, I thought, perhaps I need to write a little recursive method to go and get the parent nodes of each selected category... Turns out that because I was using acts_as_tree in the model (google it!), I was able to solve this with a really simple bit of code added to the category model :-

    def fullcategoryname
        self.ancestors().each() { |parent| fullname += + " / " }
        fullname +=

Thats nice! :) Gotta like Ruby.

Posted on Friday, December 14, 2007 12:00 PM rails , .net , software | Back to top

Comments on this post: Categories in Rails

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Matt Roberts | Powered by: