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?
+4
A:
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.
Jaime Bellmyer
2010-01-26 03:44:40
Thanks, worked like a charm.
2010-01-26 17:56:10