使用用户名自定义Rails网址 [英] customize rails url with username

查看:86
本文介绍了使用用户名自定义Rails网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制Twitter个人资料页面,并使用一个带有用户名 http:// www的URL .my-app.com / username ,虽然我可以在地址栏中手动输入该名称并导航到个人资料页面,但无法链接到自定义网址。

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.

我认为问题出在路线上-这是我的路线中的代码。rb

I think the problem is in the routes - here's the code in my routes.rb

map.connect '/:username', :controller => 'users', :action => 'show'

此外,我还有问题 Answer 模型,我想使用自定义网址链接到它们,如下所示:

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'

只需草稿即可扩展。

这篇关于使用用户名自定义Rails网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆