views:

448

answers:

2

Morning Everyone!..

General Routing Quesiton Here... I'm currently working to achieve a route similar to this for users in my application.

http://www.example.com/username

This then maps to the usersControllers#show, hence I have the following in my routes file.

map.connect '/:permalink', :controllers => "users", :action => "show"

I've then got the show action to find the user by the permalink in the param. So its works but....

The problem I'm running into is that all other UNDEFINED routes get sent to userController#show. i.e 404's & other un-named routes. So I dont think i'm going with the right convention for this. My solution is to just add other named routes above this, which solves the problem, but to me seems brittle. Am I thinking about this wrong?

Whats a better solution? I'm going to mine google for answers but I just thought i'd throw this up for discussion. Ideas?

+1  A: 

You're doing it right. Rails routes go from high priority at the top to low priority at the bottom. Your users show action should go at the bottom. Just make sure that if the permalink does not correspond to a user a proper 404 is generated.

Ben Hughes
Thanks Ben, I appreciate the heads up. I think I've worked this out. I've defined the "permalink" namespace and all other existing urls I have listing above as higher priority. Testing it now...
Nick L
+1  A: 

What if you get a user whose username is the same as other URLs on your site? This seems like a trouble waiting to happen.

Just change it to http://www.example.com/user/username

This way you create a "user" namespace for all username based URLs.

Zepplock
Zepplock, Yeah i was considering that. But i really like the look of urls having their own profils directly after the "root" namespace. I'm going to build in validation to prevent users from creating names that match existing URLS, or even further have those more "static" urls in their own namespace instead.. i.e www.example.com/pages/.... . Thanks for the tip though!
Nick L
/user/username is cumbersome. Just add or otherwise restrict usernames from being the same as other controller paths. Worst case, because the user path would be a low priority route, would be that a user is inaccessible. Even this is solvable by enforcing some data rules.
Ben Hughes