路由路径的语法差异

时间:2018-03-05 09:17:18

标签: ruby-on-rails routes

在rails路由文件中,指定

Rails.application.routes.draw do
  namespace :api, defaults: { format: :json }, :constraints => {:subdomain => "api"}   do

将在api.domain.tld/api/[...]

生成操作网址

要删除重复,可以指定路径。不过,我已经看到了:path => "",:path => "/",的建议。

两者之间有什么实际区别?

1 个答案:

答案 0 :(得分:1)

:path => "":path => "/"

之间没有区别

例如,使用rake routes

routes.rb (路径中没有正斜杠)
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中正确放置正斜杠,并允许开发人员在语法上更灵活。所以实际上,无论你是否提出斜线都没关系。