Rails:将子域路由到资源

Hom*_*mar 8 subdomain routing ruby-on-rails

是否可以将子域映射到资源?我有一个公司模特.目前,使用subdomain_fu,我的路由文件包含:

map.company_root  '', :controller => 'companies', :action => 'show',
                      :conditions => { :subdomain => /.+/ }
Run Code Online (Sandbox Code Playgroud)

我的公司模型包含"子域"列.

虽然这是按预期工作的,但它是一条命名的路线而且并不安宁.基本上,我需要将"name.domain.com"映射到公司控制器的show动作.命名路由是可行的,还是可以使用资源路由?

Ste*_*ham 8

可以将条件传递给资源路由以及命名路由.在我参与的应用程序中,所有内容都限定在一个帐户中.答:before_filter使用子域加载帐户.因此,对于作用于帐户的资源,我们希望将路由范围限定为具有子域的URL.DRY方式是使用带有选项的地图:

  map.with_options :conditions => {:subdomain => /.+/} do |site|
    site.resources :user_sessions, :only => [:new, :create, :destroy]
    site.resources :users
    site.login 'login', :controller => "user_sessions", :action => "new"
    site.logout 'logout', :controller => "user_sessions", :action => "destroy"
    …
  end

  map.connect 'accounts/new/:plan', :controller => "accounts", :action => "new"
  map.resources :accounts, :only => [:new, :create]
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,命名路由也将接受带有子域的条件哈希.您也可以采用上面说明的Ryan方法,或者您可以基于每个资源指定条件:

  map.resources :users, :conditions => {:subdomain => /.+/}
Run Code Online (Sandbox Code Playgroud)


rya*_*anb 4

我不知道有什么方法可以做到这一点map.resources。它确实接受一个:conditions选项,但我不确定如何删除/companies/URL 的部分。然而,map.resources这主要是生成一堆命名路由的便捷方法,您可以手动执行此操作。像这样的东西。

map.company '', :controller => 'companies', :action => 'show', :conditions => { :subdomain => /.+/, :method => :get }
map.new_company 'new', :controller => 'companies', :action => 'new', :conditions => { :subdomain => /.+/, :method => :get }
map.edit_company 'edit', :controller => 'companies', :action => 'edit', :conditions => { :subdomain => /.+/, :method => :get }
map.connect '', :controller => 'companies', :action => 'create', :conditions => { :subdomain => /.+/, :method => :post }
map.connect '', :controller => 'companies', :action => 'update', :conditions => { :subdomain => /.+/, :method => :put }
map.connect '', :controller => 'companies', :action => 'destroy', :conditions => { :subdomain => /.+/, :method => :delete }
Run Code Online (Sandbox Code Playgroud)

未经测试,但它应该会让你接近。