在 Rails 的显示页面中将 user_id 替换为用户名
天哪,
我想在用户的显示页面中显示用户名而不是 user_id 。
例如,
数据库中存在名为 harry 的用户的 usr_id 300。那么如何展示
而不是
网址中的
。这可以在路由文件中完成吗?
谢谢
Hell frens
I want to show a username instead of user_id in user's show page.
For example,
a usr_id 300 for a user named harry exist in database. So how to show
instead of
in the url.
Can this be done within from the routes file?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这通常被称为虚荣 URL,只要稍加小心,您就可以很容易地处理它。首先...
在您的路线中:
在上面的代码中,为了清楚起见,我避免为每个路线重复
:constrain
选项。您需要调整正则表达式以匹配您的用户名,然后确保您选择的任何路线上都有它。如果这将成为从应用程序内访问用户的默认方式(即不仅仅是访问用户个人资料的便捷方式),您将需要重写您的应用程序中的
to_param
方法。用户模型。这允许您使用url_for
帮助器,例如form_for @user
,而无需指定其他参数。另一个快速提示:如果您正在使用路线并尝试执行基础以外的任何操作,请务必经常从命令行调用 $ rake paths 来查看 Rails 当前识别的路线。清理不需要的东西也是一件好事。 ;)
This is commonly referred to as a vanity URL, and with a little caution you can handle this quite easily. First...
In your routes:
In the above code, I avoided duplicating the
:constrain
option for each route for clarity. You will want to adjust the regular expression to match your usernames, and then make sure you do have it on whichever route you go with.If this is going to be the default way of accessing users from within your application (ie. not just a convenient way to access the profile of a user), you will want to override the
to_param
method on your Users model. This allows you to use theurl_for
helpers likeform_for @user
without specifying additional arguments.Another quick tip: if you're playing with your routes and trying to do anything more than the basics, be sure to call
$ rake routes
often from the command line to see what routes Rails currently recognizes. Cleaning up ones you don't need is good to do, too. ;)如果你想有 /:username,那么在你的 paths.rb 文件中尝试这个(这应该是块的最后一行! - 最后创建的路由!)
然后,为了让它不那么可怕,你可以使用 make_permalink gem 轻松创建友好的 url 名称并覆盖模型中的 to_param 方法
为了使它更好,覆盖通过永久链接或通过 id 工作的 User.find 方法
适用于 User.find(1) 或 User.find(my_username)。
希望有帮助,
尼古拉斯·霍克·伊萨萨
If you want to have /:username, then try this on your routes.rb file (THIS SHOULD BE THE LAST LINE OF THE BLOCK! - Last route created!)
Then, just to make it less horrible, you can use the make_permalink gem to create friendly url-names easily and override the to_param method in your model
And to make it even better, override the User.find method to work by permalink or by id
That will work for User.find(1) or User.find(my_username).
Hope that helps,
Nicolás Hock Isaza
在 paths.rb 中尝试类似的东西,
稍后在视图中使用它,如下所示:
我不确定代码是否可以简单地通过粘贴来工作,但你明白了:)
try something like this in routes.rb
later in views use it like this:
I'm not sure if code will work simply by paste it, but you get the point :)
对于 Rails 7:
在 config/routes.rb
中,添加:app/models/user.rb
中,添加:For rails 7:
In config/routes.rb
, add:app/models/user.rb
, add: