views:

123

answers:

3

I've seen and googled and found many pretty url links.

But they all seem to look like http://example.com/users/username

I want it to be like github style http://example.com/username

Any directions that I can follow??

A: 

Isn't that you just need to drop users/ in routes?

map.connect '/:username',... instead of map.connect '/users/:username',...

S.Mark
+1  A: 

A very Basic example could be this:

  • declare a route with lowest priority pointing to your users controller's show action
  • modify the show action to find records based on username

In config/routes.rb:

map.username '/:username', :controller => :users, :action => :show

In UsersController:

def show
  @name = Name.find_by_name(params[:username]) || Name.find(params[:id])
end

You can then use username_path(:username => user.name) to generate links.

mikezter
+2  A: 

What's wrong with http://example.com/users/username? The problem with using http://example.com/username is that someone could very easily register the username admin or faq which could conflict with your other routes. You'll need to keep a list of prohibited usernames and also you'll need to check if a user exists with a given name before you create a new route, as that might conflict with an existing user.

You could always shorten it to: http://example.com/u/username.

However, if you must do this you can use map.connect as others have suggested, but you should definitely think about the pros and cons and whether or not it adds any significant value.

jonnii
To be fair you should always have a username blacklist because a user named admin or webmaster is a bad no matter what never mind simply conflicting with routes.
srboisvert
Yup, but I've found this solution here http://henrik.nyh.se/2008/10/validating-slugs-against-existing-routes-in-railsI think I'll go with this solution.
Millisami
I'm glad you've found something that works for you. Make sure when you introduce a new route you do the inverse check.
jonnii