Rails : 将命名空间添加到资源

Rails : add namespace to resource

目前我的 routes.rb 中有这个:

namespace :api
  namespace :v1
   namespace :me
    # ...
    resources :offers do
     resources :state, only: %i(index)
    end
  end
 end
end

这给了我这条路线:

GET v1/me/offers/:offer_id/state(.:format)
api/v1/me/state#index

但我想要的路线是这条路线:

GET v1/me/offers/:offer_id/state(.:format)
api/v1/me/offers/state#index

简而言之,我希望能够将我的 state_controller.rb 放在 offers 文件夹中,而无需更改访问它的路径。 我怎样才能做到这一点?

您应该明确地为您的资源定义控制器:

resources :state, controller: 'offers/state'

这会将请求路由到 app/controllers/api/v1/me/offers/state_controller.rb

namespace :api
  namespace :v1
   namespace :me
    # ...
    resources :offers do
      namespace :offers, path: "" do
        resources :state, only: %i(index)
      end
    end
  end
 end
end

我找到了更好的方法:使用 module

resources :offers, module: :offers do
  resources :state, only: %i(index)
end