我有一个Rails 4应用程序,其中所有控制器和视图分为两个名称空间,面向代理backend
和面向客户frontend
:
MyApp::Application.routes.draw do
constraints subdomain: "admin" do
namespace :backend do
resources :events
end
end
constraints subdomain: /.+/ do
namespace :frontend do
resources :events
end
end
end
此外,所有控制器都继承自BackendController
或FrontendController
:
controllers
├── application_controller.rb
├── backend
│ ├── events_controller.rb
├── backend_controller.rb
├── frontend
│ └── events_controller.rb
├── frontend_controller.rb
现在,需要生成路径的所有内容都必须以命名空间为前缀,例如respond_with [:backend, @event]
或form_for [:backend, @event]
。
有没有办法为每个控制器的URL助手设置一个默认命名空间,以便从继承自BackendController的控制器调用的respond_with @event
会自动假定正确的命名空间?
答案 0 :(得分:0)
您可以在路线文件中使用scope module: :backend
代替namespace :backend
。
如果您希望模块名称显示在URL中,您也可以向范围添加:path
选项。
考虑以下路线文件:
Rails.application.routes.draw do
scope module: 'backend1' do
resources :event1
end
scope module: 'backend2', path: 'backend3' do
resources :event2
end
namespace 'backend3' do
resources :event3
end
end
这将产生以下路线:
Prefix Verb URI Pattern Controller#Action
event1_index GET /event1(.:format) backend1/event1#index
POST /event1(.:format) backend1/event1#create
new_event1 GET /event1/new(.:format) backend1/event1#new
edit_event1 GET /event1/:id/edit(.:format) backend1/event1#edit
event1 GET /event1/:id(.:format) backend1/event1#show
PATCH /event1/:id(.:format) backend1/event1#update
PUT /event1/:id(.:format) backend1/event1#update
DELETE /event1/:id(.:format) backend1/event1#destroy
event2_index GET /backend3/event2(.:format) backend2/event2#index
POST /backend3/event2(.:format) backend2/event2#create
new_event2 GET /backend3/event2/new(.:format) backend2/event2#new
edit_event2 GET /backend3/event2/:id/edit(.:format) backend2/event2#edit
event2 GET /backend3/event2/:id(.:format) backend2/event2#show
PATCH /backend3/event2/:id(.:format) backend2/event2#update
PUT /backend3/event2/:id(.:format) backend2/event2#update
DELETE /backend3/event2/:id(.:format) backend2/event2#destroy
backend3_event3_index GET /backend3/event3(.:format) backend3/event3#index
POST /backend3/event3(.:format) backend3/event3#create
new_backend3_event3 GET /backend3/event3/new(.:format) backend3/event3#new
edit_backend3_event3 GET /backend3/event3/:id/edit(.:format) backend3/event3#edit
backend3_event3 GET /backend3/event3/:id(.:format) backend3/event3#show
PATCH /backend3/event3/:id(.:format) backend3/event3#update
PUT /backend3/event3/:id(.:format) backend3/event3#update
DELETE /backend3/event3/:id(.:format) backend3/event3#destroy
希望有所帮助!