Many social networking sites like Twitter have “pretty urls” that get you to a user’s profile in the fewest possible keystrokes. Their format is usually
http://example.com/username, and it’s easy to add this to your own Rails application.
Let’s say you have a restful profiles controller that we use for the public-facing aspects of a user. Put this in your routes file:
# config/routes.rb ActionController::Routing::Routes.draw do |map| map.resources :profiles map.resources :users map.profile_link '/:login', :controller => 'profiles', :action => 'show' map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end
Notice we have our special named route “profile_link” after our resources. The Rails routing file works top-to-bottom, meaning Rails will grab the first route that matches the incoming url. If we put our profile_link route in front of the resources, this would confuse the routing engine and some of our restful routes would fail.
Now we need to setup our show action to use the login parameter to find the correct user:
# app/controllers/profiles_controller.rb class ProfilesController < ApplicationController def show @user = User.find_by_login(params[:login]) end end
Of course, you’ll need corresponding view code in
app/views/profiles/show.html.erb as well.
That’s all it takes to get short, sweet vanity urls in your rails application.