我有一堆资源想在 /api/[PATH]
和 /api/v1/[PATH]
中提供。换句话说,/api/tasks/12
和 /api/v1/tasks/12
都应该被路由到 Api::V1::TasksController#show
。但是,出于向后兼容性的原因,我不想使用外部重定向 - 所有路由都应该在内部进行。
这是迄今为止我发现的最好的,但它需要复制 resource
声明:
namespace :api, defaults: {format: :json} do
namespace :v1, as: 'v1' do
resource :profile, only: [:show]
resources :notifications, only: [:create]
resources :tasks, only: [:index, :create, :show, :update]
end
scope module: 'v1' do
resource :profile, only: [:show]
resources :notifications, only: [:create]
resources :tasks, only: [:index, :create, :show, :update]
end
end
是的,如果我真的想避免重复,我可以将它们放在 Proc 中,但这看起来很荒谬。
我尝试了类似 match '*path', path: '/v1', via: :all
的方法(在第一个 namespace
内),但这似乎不起作用。
肯定有更好的方法吗?
最佳答案
路线
我理解您的问题 - 您希望为 /v1
API 定义与标准 /api
相同的路由(包括 Controller )。
我最多只能帮助您定义一些 routing concerns :
#config/routes.rb
concern :api do
resource :profile, only: [:show]
resources :notifications, only: [:create]
resources :tasks, only: [:index, :create, :show, :update]
end
namespace :api, defaults: {format: :json} do
scope module: "v1" do
concerns :api
end
namespace :v1, as: 'v1' do
concerns: :api
end
end
我知道这有点 WET,但这是实现您正在寻找的东西的最可靠方法
关于ruby-on-rails - 如何在 Rails 4 中将一组资源路由别名或重写到另一个命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25319226/