How to setup github.com like username url?
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开发者_如何学Python github style http://example.com/username
Any directions that I can follow??
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.
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.
Isn't that you just need to drop users/
in routes?
map.connect '/:username',...
instead of map.connect '/users/:username',...
精彩评论