Ruby on rails 如何将API端点添加到现有Rails 4应用程序?

Ruby on rails 如何将API端点添加到现有Rails 4应用程序?,ruby-on-rails,Ruby On Rails,我在用Rails 4构建的应用程序中添加了一个API。我在谷歌上搜索了一些东西,这就是我想到的 在my routes.rb中 My normal html view endpoints up here ........... ........... # API require 'api_constraints' namespace :api, defaults: { format: :json }, path: nil, constraints: { subdomain: 'ap

我在用Rails 4构建的应用程序中添加了一个API。我在谷歌上搜索了一些东西,这就是我想到的

在my routes.rb中

 My normal html view endpoints up here
 ...........
 ...........

 # API
 require 'api_constraints'

 namespace :api, defaults: { format: :json }, path: nil, constraints: { subdomain: 'api' } do
   scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
     resources :users, only: :show
   end
 end
My 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.MYAPP.v#{@version}")
 end
end
我的bas api控制器
(controllers/api\u controller.rb)

我遇到的问题是,当我访问
api.MYAPP.com/users/USERID
时,它只是指向普通用户\u controller.rb,向我显示html视图,而它应该路由到api/v1/users\u controller.rb

当我跑耙子路线时,我会

user GET/users/:id(:format)users#show

api\u user GET/users/:id(:format)api/v1/users\show{:format=>:json,:subdomain=>“api”}

如果我更改api名称空间,使url中的版本如下

 namespace :api, defaults: { format: :json }, path: nil, constraints: { subdomain: 'api' } do
   namespace :v1 do
     resources :users, only: :show
   end
 end
当我访问
api.myapp.com/v1/users/USERID

我做错了什么

class Api::V1::UsersController < Api::V1::ApiController
 respond_to :json

 def show
   respond_with User.find(params[:id])
 end
end
 namespace :api, defaults: { format: :json }, path: nil, constraints: { subdomain: 'api' } do
   namespace :v1 do
     resources :users, only: :show
   end
 end