Rails 3 - 两个子域的相同控制器不同的范围

时间:2012-01-01 16:40:39

标签: ruby-on-rails ruby-on-rails-3 routing routes subdomain

我想为2个子域使用相同的控制器,但范围不同。

例如(在我的routes.rb中):

constraints :subdomain => "admin" do
  resources :photos
end

constraints :subdomain => "www" do
  scope "/mystuff"
    resources :photos
  end
end

现在,当我运行“rake routes”时,我同时拥有“/ mystuff / photos”和“/ photos”。

我有两个问题:

  1. 这样做可以吗?
  2. 在这种情况下如何使用命名路由?我有类似admin_photos_url和www_photos_url的内容吗?

1 个答案:

答案 0 :(得分:4)

我认为这样做很好...... Rails中的路由选择是灵活的(因为这样的情况)。

但是,为了正确命名你的路径助手,我会更改你的路线更像这样:

scope :admin, :as => :admin, :constraints => { :subdomain => "admin" } do
  resources :photos
end

scope '/mystuff', :as => :mystuff, :constraints => { :subdomain => "www" } do
  resources :photos
end

哪个会给你:

      admin_photos    GET    /photos(.:format)                      {:subdomain=>"admin", :action=>"index", :controller=>"photos"}
                      POST   /photos(.:format)                      {:subdomain=>"admin", :action=>"create", :controller=>"photos"}
   new_admin_photo    GET    /photos/new(.:format)                  {:subdomain=>"admin", :action=>"new", :controller=>"photos"}
  edit_admin_photo    GET    /photos/:id/edit(.:format)             {:subdomain=>"admin", :action=>"edit", :controller=>"photos"}
       admin_photo    GET    /photos/:id(.:format)                  {:subdomain=>"admin", :action=>"show", :controller=>"photos"}
                      PUT    /photos/:id(.:format)                  {:subdomain=>"admin", :action=>"update", :controller=>"photos"}
                      DELETE /photos/:id(.:format)                  {:subdomain=>"admin", :action=>"destroy", :controller=>"photos"}
    mystuff_photos    GET    /mystuff/photos(.:format)              {:subdomain=>"www", :action=>"index", :controller=>"photos"}
                      POST   /mystuff/photos(.:format)              {:subdomain=>"www", :action=>"create", :controller=>"photos"}
 new_mystuff_photo    GET    /mystuff/photos/new(.:format)          {:subdomain=>"www", :action=>"new", :controller=>"photos"}
edit_mystuff_photo    GET    /mystuff/photos/:id/edit(.:format)     {:subdomain=>"www", :action=>"edit", :controller=>"photos"}
     mystuff_photo    GET    /mystuff/photos/:id(.:format)          {:subdomain=>"www", :action=>"show", :controller=>"photos"}
                      PUT    /mystuff/photos/:id(.:format)          {:subdomain=>"www", :action=>"update", :controller=>"photos"}
                      DELETE /mystuff/photos/:id(.:format)          {:subdomain=>"www", :action=>"destroy", :controller=>"photos"}