Yesterday I was implementing a feature in a Ruby on Rails application, and it occurred to me to mention that aside from providing a strong basic framework for creating Web applications, Rails also generally nails the details. Our application has a basic paginated list view, and I needed to make the view sortable by the various columns. This is, of course, a standard feature of just about any decent Web application that displays data in tables, and I’ve implemented such views in Java, PHP, Perl, ColdFusion, and probably five other things that I can’t remember.

Pagination features are already built into Ruby on Rails. Paginating query results is as simple as indicating how many items will appear on each page, and specifying which page you want to retrieve. Rails will even generate the page links for you. This get a bit more complex when you add sorting to the mix. To do sorting right, you need two parameters — the field to sort on and the sort order (ascending or descending). In actuality, you only need to use the sort order parameter when you’re sorting stuff in descending order. Ascending is usually the default.

This may sound relatively simple, but it quickly turns into a big mess of parameters. To keep things under control, you have to keep track of the page number, the two sort fields, and any parameters necessary to put the right records on the page in the first place. Needless to say, this sort of thing can get rather painful, especially because you have to write out lots of custom links. Each page number link has to encapsulate all of this information, as do all of the sort links.

I’ve done it all many times before, as I said, so the question was whether Rails would make doing it any easier. Somewhat surprisingly, the answer was yes. First of all, Rails has a method just for building links. Here’s the code that produces one of the links in the column headings on my report:

<%= link_to "ID", { :action => controller.action_name, :controller => controller.controller_name, :page => params[:page], :ob => ‘id’, :so => (params[:so] != “d”) ? “d” : nil } %>

“ID” is the link text, and the rest of the parameters are an associative array. The link_to method doesn’t understand all of them, it just knows that any parameters it doesn’t recognize should be converted to URL parameters in the link. It’s smart enough to drop any parameters that are set to nil, so if there’s no page number, it just leaves that parameter out of the URL entirely.

I don’t want to bore you with lots more code, but suffice it to say that Rails makes this sort of thing really easy. It’s gratifying to use a framework that was obviously built by people who understand the real problems developers run into. I imagine that most of the features like these are a result from the large pool of Rails contributors, many of whom are adding little bits that make things a bit more elegant.