If you're a Rails developer who wants users to actually visit your application once in awhile, it would help to pay some attention to the little white box at the top of your browser.  Right now, it probably says:

http://localhost:3000/bacon/show/31

While the URL appears clean to us programmer-types, there's plenty of room for improvement.  The main problem is that the ID, 31, has meaning only in the context of your application.  When the URL shows up somewhere else, it's just a number.  This matters a tiny bit to humans, and a lot more to search engines.  We'd like to put something there that tells what 31 actually is.  In my last app, my first attempt at URL beautification looked like this:

http://localhost:3000/bacon/show/Wood-Smoked

That's a good start: it loads the URL with more information about what's being displayed, and the dash as word separator is search engine friendly.  However, this setup still has problems:  what if two bacons have identical names?  This actually happened in my app, where several categories were named "General".  Also, what if we change the name of a bacon?  Then, references to the old name in the URL won't work.  That stinks!

I'll spare you the further thought exercise and say that someone else has already done the hard work for you.  His post on Transparent opaque changeable permanent URLs is a masterful dissection of both problem and solution.  In short, his solution is to put both the id AND the title / whatever into the "slug" (that thing at the end of the URL that we're concentrating on), and to redirect users if they get the ID right but use an old or incorrect title.  Sweet!  If you're like me, however, you wished for one more thing: spoonfed Rails code.  I found some of that, too, at URLs on Rails.  Finally, the author mentions implementation of the redirect for incorrect slugs but doesn't show the code.  He's right, it's easy, and here's how I did it:

@bacon = Bacon.find(params[:id])
if params[:id] != @bacon.to_param
  headers["Status"] = "301 Moved Permanently"
  redirect_to :id => @bacon and return
end

Now you should have all the code you need to build bulletproof, search engine-friendly URLs into your app.  Enjoy the bacon!

Tags: