Clear, usable interfaces. Clean, accessible code.

Route 19

Logbook.

Simple Rails Permalink Nov. 23 at 12:15 pm

The simplest way to add friendlier URIs with Rails 2.x is with the model’s to_param method. Requires no database changes and works with existing objects.

So a URI like this:
http://route19.com/logbook/123
Becomes:
http://route19.com/logbook/123-title-converted-to-uri

Adding the to_param method to your model, and starting it’s return value with the original object id allows you to tack on pretty much anything you want, in this case the title formatted for use in the URI. When rails converts that value to an integer for the database call, the non digit characters are ignored, and the ID is used as usual.

UPDATE:

Rails 2.3.2 introduced the parameterize method, which replaces the previously recommended use of gsub.

class Post < ActiveRecord::Base
  def to_param
    "#{id}-#{title. parameterize}"
  end
end

Older versions of Rails can use the gsub below to handle basic characters, you may need to make it more robust for accents, etc.

class Post < ActiveRecord::Base
  def to_param
    "#{id}-#{permalink}"
  end
  def permalink
    title.gsub(/\s/, '-').gsub(/[^\w-]/, '').downcase
  end
end

Recent Entries

More