没有路由匹配[GET] /用户

Jea*_*ent 3 ruby routes ruby-on-rails

编辑:由于评论中写的反馈,资源和控制器已经多元化.但我的问题仍然存在.

我是Rails的新手,我正在尝试在Rails 4中创建REST API.当我尝试在Userressource 上执行GET请求时,我遇到了路由错误:http://api.localhost:3000/users

没有路线匹配[GET]"/ users"

但是,当我在终端上执行命令'rake routes'时,我可以看到有一条/users路线:

    api_users GET    /users(.:format)          api/users#index {:subdomain=>"api"}
              POST   /users(.:format)          api/users#create {:subdomain=>"api"}  
 new_api_user GET    /users/new(.:format)      api/users#new {:subdomain=>"api"}
edit_api_user GET    /users/:id/edit(.:format) api/users#edit {:subdomain=>"api"}
     api_user GET    /users/:id(.:format)      api/users#show {:subdomain=>"api"}
              PATCH  /users/:id(.:format)      api/users#update {:subdomain=>"api"}
              PUT    /users/:id(.:format)      api/users#update {:subdomain=>"api"}
              DELETE /users/:id(.:format)      api/users#destroy {:subdomain=>"api"}
Run Code Online (Sandbox Code Playgroud)

这是我的route.rb文件的内容:

Rails.application.routes.draw do

  # create rousources in subdomain api
  namespace :api, path: '/', constraints: { subdomain: 'api' } do
    resources :users
  end

end
Run Code Online (Sandbox Code Playgroud)

users_controller.rb文件:

module Api
    class UsersController < ApplicationController

        def index
            @users = User.all

            render json: users, status: 200
        end

    end
end
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?

编辑:由于评论中写的反馈,资源和控制器已经多元化.但我的问题仍然存在.

spi*_*ann 8

Rails subdomain通过从右边第二个点前面的主机地址中获取该部分来确定URL.在您的示例中,您使用主机api.localhost.Rails将从中解析空子域.

因此,我建议api.my_app.dev您在hosts文件中配置域名.这将允许Rails api从主机确定正确的子域部分.

完成后,您的本地服务器可以响应 http://api.my_app.dev:3000/users

顺便说一句.我选择了顶级域名dev,因为如果您使用像POW这样的工具,它是默认的.