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

六月ゝ 毕业季﹏ 提交于 2019-12-01 10:08:32

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1049455/rails-routing-question-mapping-slugs-permalinks-directly-under-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!