在rails路由文件中,指定
Rails.application.routes.draw do
namespace :api, defaults: { format: :json }, :constraints => {:subdomain => "api"} do
将在api.domain.tld/api/[...]
要删除重复,可以指定路径。不过,我已经看到了:path => "",
和:path => "/",
的建议。
两者之间有什么实际区别?
答案 0 :(得分:1)
:path => ""
和:path => "/"
例如,使用rake routes
namespace(:api_namespace, :path=>"v1", :constraints => {:subdomain => "api_subdomain"}) do
resources :todos
end
生成的路线是
api_namespace_todos GET /v1/todos(.:format) api_namespace/todos#index {:subdomain=>"api_subdomain"}
POST /v1/todos(.:format) api_namespace/todos#create {:subdomain=>"api_subdomain"}
new_api_namespace_todo GET /v1/todos/new(.:format) api_namespace/todos#new {:subdomain=>"api_subdomain"}
edit_api_namespace_todo GET /v1/todos/:id/edit(.:format) api_namespace/todos#edit {:subdomain=>"api_subdomain"}
api_namespace_todo GET /v1/todos/:id(.:format) api_namespace/todos#show {:subdomain=>"api_subdomain"}
PUT /v1/todos/:id(.:format) api_namespace/todos#update {:subdomain=>"api_subdomain"}
DELETE /v1/todos/:id(.:format) api_namespace/todos#destroy {:subdomain=>"api_subdomain"}
并使用routes.rb(在路径中使用正斜杠)
namespace(:api_namespace, :path=>"/v1", :constraints => {:subdomain => "api_subdomain"}) do
resources :todos
end
或
namespace(:api_namespace, :path=>"v1/", :constraints => {:subdomain => "api_subdomain"}) do
resources :todos
end
使用上述代码生成的路由
api_namespace_todos GET /v1/todos(.:format) api_namespace/todos#index {:subdomain=>"api_subdomain"}
POST /v1/todos(.:format) api_namespace/todos#create {:subdomain=>"api_subdomain"}
new_api_namespace_todo GET /v1/todos/new(.:format) api_namespace/todos#new {:subdomain=>"api_subdomain"}
edit_api_namespace_todo GET /v1/todos/:id/edit(.:format) api_namespace/todos#edit {:subdomain=>"api_subdomain"}
api_namespace_todo GET /v1/todos/:id(.:format) api_namespace/todos#show {:subdomain=>"api_subdomain"}
PUT /v1/todos/:id(.:format) api_namespace/todos#update {:subdomain=>"api_subdomain"}
DELETE /v1/todos/:id(.:format) api_namespace/todos#destroy {:subdomain=>"api_subdomain"}
在两种情况下使用正斜杠(即。/)和而不使用正斜杠生成的路线正好相同。
它的rails正在处理在URL中正确放置正斜杠,并允许开发人员在语法上更灵活。所以实际上,无论你是否提出斜线都没关系。