如何路由用户个人资料URL以跳过控制器? [英] How do I route user profile URLs to skip the controller?
问题描述
现在我的用户个人资料网址如下:
Right now my user profile URLs are like so:
http://example.com/users/joeschmoe
这指向显示
用户控制器中的方法。
And that points to the show
method in the user controller.
我理想地要做的是提供这样的用户个人资料网址:
What I'd ideally like to do is offer user profile URLs like this:
那么,需要什么样的路线和控制器魔术才能实现这一目标?
So, what sort of route and controller magic needs to happen to pull that off?
推荐答案
我不同意jcm说一下。这根本不是一个可怕的主意,并且被两个最大的社交网络Facebook和MySpace用于生产。
I disagree with what jcm says about this. It's not a terrible idea at all and is used in production by the two biggest social networks Facebook and MySpace.
匹配 http:/的路线/example.com/username
看起来像这样:
map.connect ':username', :controller => 'users', :action => 'show'
如果您想走子网域路线并将配置文件映射到类似<$ c的URL $ c> http://username.example.com/ ,我建议使用SubdomainFu插件,结果路由如下:
If you want to go the subdomain route and map profiles to a URL like http://username.example.com/
, I recommend using the SubdomainFu plugin and the resulting route would look like:
map.root :controller => 'users', :action => 'show' , :conditions => {:subdomain => /.+/}
这些广泛的,捕获的所有路由都应该在routes.rb中最后定义
These broad, catch all routes should be defined last in routes.rb, so that they are of lowest priority, and more specific routes will match first.
我还建议在用户模型中使用验证,以消除用户选择用户名的可能性
I also recommend using a validation in your User model to eliminate the possibility of a user choosing a username that will collide with current and future routes:
class User < ActiveRecord::Base
validates_exclusion_of :username, :in => %w( messages posts blog forum admin profile )
…
end
这篇关于如何路由用户个人资料URL以跳过控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!