问题描述
我想复制 Twitter 个人资料页面并有一个用户名为http://www.my-app.com/username",虽然我可以在地址栏中手动输入它并导航到个人资料页面,但我无法链接到自定义 URL.
I want to copy the twitter profile page and have a url with a username "http://www.my-app.com/username" and while I can manually type this into the address bar and navigate to the profile page I can't link to the custom URL.
我认为问题出在路线上 - 这是我的 routes.rb 中的代码
I think the problem is in the routes - here's the code in my routes.rb
map.connect '/:username', :controller => 'users', :action => 'show'
此外,我有 Question
和 Answer
模型,我想使用自定义 URL 链接到它们,如下所示:
Also, I have Question
and Answer
models and I want to link to them with the customized URL like so:
http://www.my-app.com/username/question/answer/2210
推荐答案
您的路线没有任何问题.在定义所有其他路由之后,请记住在最后定义它.我还建议使用 RESTful 路由,并且仅当您想要更好看的 URL 时才使用命名路由.不要使用 map.connect
.这里有一些有关 Rails 路由的好读物.
There's nothing wrong with your route. Just remember to define it at the end, after defining all other routes. I would also recommend using RESTful routes and only if you want to have better looking URLs use named routes. Don't use map.connect
. Here's some good reading about Rails routes.
这是它的样子:
map.resources :questions, :path_prefix => '/:username' do |question|
question.resources :answers
end
map.resources :users
map.user '/:username', :controller => 'users', :action => 'show'
只是一个你可以扩展的草稿.
Just a draft you can extend.
这篇关于使用用户名自定义 rails url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!