如何在 Rails 应用程序中实现虚 URL? [英] How can I implement vanity URL's in a Rails application?

查看:16
本文介绍了如何在 Rails 应用程序中实现虚 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户能够在 site.com/myNameHere 上拥有个人资料页面.Rails 查找名为myNameHere"的控制器.是否可以设置 routes.rb 以便在未找到控制器时将myNameHere"作为参数发送到另一个控制器?

I want users to able to have a profile page at site.com/myNameHere. Rails looks for a controller named "myNameHere." Is it possible to setup routes.rb so that if the controller is not found, "myNameHere" gets sent as a parameter to another controller?

推荐答案

你可以像这样添加路由:

You can add a route like this:

map.profile_link '/:username', :controller => 'profiles', :action => 'show'

确保将它添加到文件中足够低的位置,在您的资源下方,以免干扰其他路由.它应该是最低优先级.接下来,您需要更改您的 show 操作以使用用户名而不是 id:

Be sure to add it low enough in the file, below your resources, that it doesn't interfere with other routes. It should be lowest priority. Next, you need to change your show action to use a username instead of id:

def show
  @user = User.find_by_username(params[:username])
end

仅此而已.快乐编码!

更新:

我已将此答案扩展为完整的博客文章,Ruby on Rails 路由中的虚 URL.我有额外的代码示例和更详尽的解释.

I've expanded this answer into a full blog post, Vanity URLs in Ruby on Rails Routes. I have additional code samples and a more thorough explanation.

这篇关于如何在 Rails 应用程序中实现虚 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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