Nick L
Nick L

Reputation: 404

Rails Routing Question: Mapping Slugs/Permalinks Directly under Root?

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?

Upvotes: 1

Views: 1389

Answers (2)

Zepplock
Zepplock

Reputation: 29175

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.

Upvotes: 0

Ben Hughes
Ben Hughes

Reputation: 14195

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.

Upvotes: 1

Related Questions