以下路由在rails routes.rb文件中定义:
require 'apiconstraints'
Rails.application.routes.draw do
namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/' do
scope module: :v1, constraints: Apiconstraints.new(version: 1, default: true) do
resources :buildings, only: [:show, :index] do
我还试图用空白来定义路径:
namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '' do
无济于事。 nginx sites-enabled文件配置如下:
server {
listen 80;
server_name api.thedomain.ws [...] thedomain.ws www.thedomain.ws
api.thedomain.ws
回应。但是,如果我致电api.thedomain.ws/v1/buildings
rails,则返回No路由匹配[GET]" / v1 / buildings"
为了完整性:
class Apiconstraints
def initialize(options)
@version = options[:version]
@default = options[:default]
end
def matches?(req)
@default || req.headers['Accept'].include?("application/vnd.v4.v#{@version}")
end
end
我在这里想念的是什么?
答案 0 :(得分:0)
namespace
宏添加"命名空间"走到路上:
Rails.application.routes.draw do
namespace :api do
resources :things
end
end
Prefix Verb URI Pattern Controller#Action
api_things GET /api/things(.:format) api/things#index
POST /api/things(.:format) api/things#create
new_api_thing GET /api/things/new(.:format) api/things#new
edit_api_thing GET /api/things/:id/edit(.:format) api/things#edit
api_thing GET /api/things/:id(.:format) api/things#show
PATCH /api/things/:id(.:format) api/things#update
PUT /api/things/:id(.:format) api/things#update
DELETE /api/things/:id(.:format) api/things#destroy
使用它的主要目的是什么。不要将路由名称空间的Rails概念与模块嵌套的语言级功能混淆。
如果您只想将控制器嵌套在模块中或添加约束,请使用scope
代替:
Rails.application.routes.draw do
scope module: :api do
resources :things
end
end
Prefix Verb URI Pattern Controller#Action
things GET /things(.:format) api/things#index
POST /things(.:format) api/things#create
new_thing GET /things/new(.:format) api/things#new
edit_thing GET /things/:id/edit(.:format) api/things#edit
thing GET /things/:id(.:format) api/things#show
PATCH /things/:id(.:format) api/things#update
PUT /things/:id(.:format) api/things#update
DELETE /things/:id(.:format) api/things#destroy
所以在你的情况下你想要:
scope defaults: { format: :json }, module: :api, constraints: { subdomain: 'api' } do
scope module: :v1, constraints: Apiconstraints.new(version: 1, default: true) do
resources :buildings, only: [:show, :index]
end
end