Vanity URLs in Ruby on Rails Routes


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.

About these ads

Tags: , , , ,

2 Responses to “Vanity URLs in Ruby on Rails Routes”

  1. Wes Says:

    And naturally, you’d want to remove the default routes since you’re using RESTful routes, right?

    • Jaime Bellmyer Says:

      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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: