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.
Tags: developers, Rails, routes, Ruby, ruby on rails
January 27, 2010 at 1:45 pm |
And naturally, you’d want to remove the default routes since you’re using RESTful routes, right?
January 27, 2010 at 3:29 pm |
Huh, that’s not a bad idea. Between RESTful routes and named routes, is there ever a good reason not to explicitly name each route? Probably not. Plus if you’re *using* the default routes anywhere, you’re probably not doing the route testing you should.
Route testing is easy, and they run super-fast, so they should be a priority. I think I have the topic for my next article!