简体   繁体   English

通过用户名路由到个人资料页面

[英]Routing to profile page by username

I am working on a social media site and I am having a problem with routing. 我正在社交媒体网站上工作,但路由遇到问题。

Every user has a profile page like facebook and this is the root I use: 每个用户都有一个个人资料页面,例如facebook,这是我使用的根目录:

get 'profile(/:id)' => 'profiles#show'

So, when the URL is like this: www.sitename.com/profile/1 it opens up the page belongs to user with id 1. But, I also want users to be able to use their usernames in url without /profile/. 因此,当URL像这样:www.sitename.com/profile/1时,它将打开属于ID为1的用户的页面。但是,我还希望用户能够使用其用户名而不使用/ profile /。 So it is gonna be like facebook. 因此,它将像facebook。

For example: www.sitename.com/handsomeboy69 例如:www.sitename.com/handsomeboy69

How can I do this in routing? 如何在路由中做到这一点? Because, rails may think that username passed in URL is a page name. 因为,Rails可能认为URL中传递的用户名是页面名称。

Thank you 谢谢

I fixed it. 我修好了它。 This is the route I used: 这是我使用的路线:

  get ':username' => 'profiles#show'

In the controller I used this statement: 在控制器中,我使用了以下语句:

if params.has_key?(:username)
  @profile = User.find_by_username(params[:username])
elsif params.has_key?(:id)
  @profile = User.find(params[:id])
else

end

else statement at the end is empty, I am gonna use that area to print out error message saying that profile cannot be found. else语句末尾为空,我将使用该区域打印出错误消息,指出找不到配置文件。

and most important part is that this routing should be at the end of the file. 最重要的部分是此路由应该在文件的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM