Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement vanity URL's in a Rails application?

I want users to able to have a profile page at site.com/myNameHere. Rails looks for a controller named "myNameHere." Is it possible to setup routes.rb so that if the controller is not found, "myNameHere" gets sent as a parameter to another controller?

like image 436
user258980 Avatar asked Jan 26 '10 03:01

user258980


1 Answers

You can add a route like this:

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

Be sure to add it low enough in the file, below your resources, that it doesn't interfere with other routes. It should be lowest priority. Next, you need to change your show action to use a username instead of id:

def show
  @user = User.find_by_username(params[:username])
end

That's all there is to it. Happy coding!

UPDATE:

I've expanded this answer into a full blog post, Vanity URLs in Ruby on Rails Routes. I have additional code samples and a more thorough explanation.

like image 79
Jaime Bellmyer Avatar answered Oct 29 '22 17:10

Jaime Bellmyer