Rails:将子域路由到资源
是否可以将子域映射到资源?我有一个公司模型。目前,使用 subdomain_fu,我的路由文件包含:
map.company_root '', :controller => 'companies', :action => 'show',
:conditions => { :subdomain => /.+/ }
我的公司模型包含“子域”列。
虽然这按预期工作,但它是一条命名路线并且并不安静。本质上,我需要将“name.domain.com”映射到公司控制器的显示操作。命名路由是可行的方法,还是可以使用资源路由?
Is it possible to map a subdomain to a resource? I have a company model. Currently, using subdomain_fu, my routing file contains:
map.company_root '', :controller => 'companies', :action => 'show',
:conditions => { :subdomain => /.+/ }
My Company model contains a "subdomain" column.
Whilst this works as intended, it's a named route and isn't restful. Essentially, I need to map "name.domain.com" to the show action for the companies controller. Is a named route the way to go, or can I use a resource route?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
人们可以将条件传递给资源路由以及命名路由。在一个应用程序中,我涉及的所有内容都仅限于一个帐户。 A :before_filter 使用子域加载帐户。因此,对于范围为帐户的资源,我们希望将路由范围限制为具有子域的 url。执行此操作的 DRY 方法是使用带有选项的映射:
如您所见,命名路由也将接受带有子域的条件哈希。您还可以采用上面介绍的 Ryan 方法,或者您可以根据每个资源指定条件:
One can pass conditions to a resource route as well as a named route. In an application I am involved with everything is scoped to an account. A :before_filter loads the account using the subdomain. Thus for resources scoped to an account, we want to scope the routes to urls with subdomains. The DRY way to do this is to use map with options:
As you can see a named route will accept a conditions hash with a subdomain too. You can also adopt the approach Ryan illustrated above or you can specify conditions on a per resource basis:
我不知道如何使用
map.resources
来做到这一点。它确实接受:conditions
选项,但我不确定如何删除 URL 的/companies/
部分。但是,map.resources 主要是生成一堆命名路由的便捷方法,您可以手动执行此操作。像这样的东西。未经测试,但它应该会让你接近。
I don't know of a way to do this with
map.resources
. It does accept a:conditions
option but I'm not sure how to remove the/companies/
portion of the URL. However,map.resources
is primarily a convenient way to generate a bunch of named routes, which you can do manually. Something like this.Untested, but it should get you close.
以下是带有身份验证的 Rails 3 子域 的完整示例实现(以及详细的教程) 。在 Rails 3 中执行此操作比在 Rails 2 中容易得多(无需插件)。
Here's a complete example implementation of Rails 3 subdomains with authentication (along with a detailed tutorial). It's much easier to do this in Rails 3 than in Rails 2 (no plugin required).
使用 Daniel 答案中链接的资源,在 Rails 3 中,根据子域将“/”路由到不同控制器的方法如下:
Using the resource linked from Daniel's answer, in Rails 3 the way to route '/' to a different controller depending on the subdomain is as follows: