Matt Roberts

Rails and .NET

  Home  |   Contact  |   Syndication    |   Login
  37 Posts | 0 Stories | 34 Comments | 35 Trackbacks

News




Twitter












Archives

Post Categories

BlogRoll

Entropy

Friday, December 14, 2007 #

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 %>
    <%= cat.name + "<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 += parent.name + " / " }
        fullname += self.name
  end

Thats nice! :) Gotta like Ruby.