Permalinks with Ruby on Rails

There are many ways to get nice looking permalinks using Ruby on Rails. By default, Rails uses the resource name and its primary key (/articles/1001 for example). I wanted something a little different for my personal website. There are more sophisticated ways to achieve this, but I went with a straight-forward approach using normal routes.

constraints year: /\d{4}/, month: /\w{3}/, day: /\d{1,2}/, permalink: /[\w\-]+/ do
  get 'articles/:year/:month/:day/:permalink', to: 'articles#show', as: :article

The other piece that makes this work is an instance method on the Article model.

def url
  ] * "/"

Now calling @article.url will return a string that can be used to link directly to an article! The controller can use any logic it wants to find the article in the database. If the permalink column is unique in the database, then it could query it directly.