16Mar Howto: Permalinks in rails
When my blog was almost done i posted it on various IRC channels to get some feedback. And one of the things that various people told me to fix was “permalinks” to posts. So i googled some on the topic and came across this article .
What this article suggest in short is that permalinks should consist of http://host/ID-TITLE and that only the ID should be essential for the server in case you change the title.
After I had read it a fired up Netbeans and started to code. And after a while I came up with this solution:
And I added this to my post model. This is a regular expression for stripping spaces and “special chars” so the permalink gets more URL-friendly.
And this into my “_post.rhtml”, the file that contains the code for rendering a post.
Pretty much the same for the “Previous posts” in the sidebar:
I want you to know that this is presumably not the best way to generate permalinks on your rails site in terms of performance. But unless you are having a really bad server or large amounts of visitors there won’t be a problem.
If you’ve got a better solution, or maybe have tweaked my code then post a comment :-)

April 17th, 2008 at 8:03 pm
tim –
I have been doing the permalinks for a site my company is managing and wanted to point out one flaw with the strategy: if you change the title (or whatever the source of the link is), the link will change, too. If the id is embedded, in the url, it will still work, but if the page has been crawled by a search engine or bookmarked anywhere, the old link will be broken.
Permalink-fu is a plugin that generates a permalink once and stores it in the database. It also uses a strategy that doesn’t require the id, although unless you’re starting from scratch, that could result in a lot of code changes in controllers and views.
Tom