gpt4 book ai didi

ruby-on-rails - 在 Rails 4 中为 URL 助手设置默认命名空间?

转载 作者:行者123 更新时间:2023-12-03 15:03:43 25 4
gpt4 key购买 nike

我有一个 Rails 4 应用程序,其中所有 Controller 和 View 都分为两个命名空间,一个面向代理的 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

此外,所有 Controller 都继承自 BackendControllerFrontendController :
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] .

有没有办法为每个 Controller 的 URL 助手设置默认命名空间,以便 respond_with @event从继承自 BackendController 的 Controller 调用自动假定正确的命名空间?

最佳答案

您可以使用 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

希望有帮助!

关于ruby-on-rails - 在 Rails 4 中为 URL 助手设置默认命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22379960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com