假如web application需要提供API時,為了讓routing有效率及提升routing table的可讀性
原本的routes.rb如下1
2
3
4
5
6
7Rails.application.routes.draw do
resources :posts # http://your-domain/posts
constraints subdomain: 'api' do
resources :contents # http://api.your-domain/contents
end
end
為了讓controller的目錄更有組織性,可以加上namespace1
2
3
4
5
6
7
8
9Rails.application.routes.draw do
resources :posts
constraints subdomain: 'api' do
namespace :api do
resources :contents # http://api.your-domain/api/contents
end
end
end
雖然controller目錄變乾淨,但URL卻多出個api/contents。
加入path1
2
3
4
5
6
7
8
9Rails.application.routes.draw do
resources :posts
constraints subdomain: 'api' do
namespace :api, path: '/' do
resources :contents # http://api.your-domain/contents
end
end
end
最後用一行搞定1
2
3
4
5
6
7Rails.application.routes.draw do
resources :posts
namespace :api, path: '/', constraints: { subdomain: 'api' } do
resources :contents
end
end