我正在学习api on rails,我的代码在
之下的routes.rb
require 'api_constraints'
Rails.application.routes.draw do
devise_for :users
namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/' do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
resources :users, :only => [:show]
end
end
end
users_controllers.rb
class Api::V1::UsersController < ApplicationController
respond_to :json
def show
respond_with User.find(params[:id])
end
end
当我使用localhost:3000/users/1
运行rails服务器时,它会给我错误No route matches
然后我使用rake routes
检查路线,它包含在我的路线
`api_user GET /users/:id(.:format) api/v1/users#show'
但我不知道为什么它会给我错误
api_constraints.rb
class ApiConstraints
def initialize(options)
@version = options[:version]
@default = options[:default]
end
def matches?(req)
@default || req.headers['Accept'].include?("application/vnd.marketplace.v#{@version}")
end
end
`
答案 0 :(得分:1)
尝试以下方法:
api.lvh.me:3000/api/v1/users/1
您已设置了需要api子域的约束。您需要删除约束才能完成以下工作:
lvh.me:3000/api/v1/users/1
注意:lvh.me指向127.0.0.1