how to get vanity urls in rails

Getting vanity urls to work in rails is very simple. Let’s say you want to allow your users to expose their Profiles through a facebook like url http://www.facebook.com/GreenDay. This is what you need to change in your routes file.

The except => :show on line#5 makes the resources helper skip the show route. And line#9 which should be at the end of the routes file, creates a route called profile which will be used for all the profile show links automatically. That’s it now your application has vanity urls, whenever someone clicks on a profile#show link they will be taken to /:slug. Obviously in this case the slug is assumed to be unique.

1
2
3
4
5
6
7
8
9
10
11
Funky::Application.routes.draw do
.
.
.
resources :profiles, :except => [:show]
.
.
#at the end of the routes file
get ':slug' => 'profiles#show', :as => 'profile'
end

###Update### One of the readers emailed me asking what the controller code would look like. Here it is:

1
2
3
4
5
6
7
8
9
10
11
#app/models/profile.rb
class Profile < ActiveRecord::Base
#should have a column called "slug"
end
#app/controllers/profiles_controller.rb
class ProfilesController < ApplicationController
def show
@profile = Profile.find_by_slug(params[:slug])
end
end

###References###


I am currently working on Zammu which makes Automatic Deployment of static websites to Github Pages very easy. I would love to get your feedback on it, Use the invitation code KHAJA