There has been quite a bit of discussion about creating permalinks with a rails resource. In this article I will show you how to create permalinks for a resource named ‘pages’ without giving up on any of the resource goodness!

Before I start I’ll presume you have a page scaffold_resource setup in your rails application. Make sure you have at least the following fields in your page model:

t.column :title, :string
t.column :content, :text


Okay, what you want is the permalink_fu plugin. This plugin greatly simplifies the act of generating a permalink from a title. Install it first:

cd railsapp


In your Page model you may now add the following line. This line will generate a permalink in the permalink attribute automatically, so you don’t have to show the permalink field in any forms.

has_permalink :title


Rails goodness has already provided you with the basic RESTful routes:

• /pages
• /pages/123
• /pages/new
• /pages/123;edit

But what you really want, is something like:

Notice that the permalink url is only a GET request and should not be used for editing or updating the page in question.

Since using any other identifier than :id in a resource is madness, I create two new routes that will allow me to access permalinked pages. Not only that, but I do maintain the format option. Basically this means that you get three routes:

Notice that I removed the ‘s’ from ‘pages’ here. This is to avoid confusion with the resource ‘pages’. But more on that later.

Now in config/routes.rb add the following two lines:

map.permalink 'page/:permalink', :controller => 'pages', :action => 'permalink'


permalink_url(@page.permalink)


The second link is unnamed, and allows you to specify a format like HTML or XML.

The permalink action looks like this:

# GET /page/perma-link