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
- Tide data for Canada Apr. 26 at 10:41 am
- Simple Referral Tracking Nov. 9 at 7:52 am
- Ruby HTML Indentation Jun. 27 at 9:47 am
- SSH Keys May. 28 at 5:01 am
- More logbook entries