【问题标题】:Rails API - LoadError in API::V1::UsersController#indexRails API - API::V1::UsersController#index 中的 LoadError
【发布时间】:2016-04-26 15:16:54
【问题描述】:

我正在尝试向我的 APP 添加一个简单的 JSON API

#routes.rb
namespace :api, :format => :json do
  namespace :v1 do
    resources :users
  end
end


#controllers/api/v1/users_controller.rb
class Api::V1::UsersController < ApplicationController
  respond_to :json

  def index
    respond_with User.all
  end
end


#inflections.rb
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'API'
end

rake routes 给了我以下信息:

api_v1_users        GET      /api/v1/users(.:format)             api/v1/users#index
                    POST     /api/v1/users(.:format)             api/v1/users#create
new_api_v1_user     GET      /api/v1/users/new(.:format)         api/v1/users#new
edit_api_v1_user    GET      /api/v1/users/:id/edit(.:format)    api/v1/users#edit
api_v1_user         GET      /api/v1/users/:id(.:format)         api/v1/users#show
                    PATCH    /api/v1/users/:id(.:format)         api/v1/users#update
                    PUT      /api/v1/users/:id(.:format)         api/v1/users#update
                    DELETE   /api/v1/users/:id(.:format)         api/v1/users#destroy

当我访问http://localhost:3000/api/v1/users 时出现以下错误:

API::V1::UsersController#index 中的LoadError 无法自动加载 常量 API::V1::UsersController,预期 /path/to/app/controllers/api/v1/users_controller.rb 来定义它

【问题讨论】:

    标签: ruby-on-rails api


    【解决方案1】:

    错误消息准确地说明了要做什么。确保在控制器名称中使用 API 而不是 Api

    #  == HERE ==
    class API::V1::UsersController < ApplicationController
      respond_to :json
    
      def index
        respond_with User.all
      end
    end
    

    【讨论】:

    • 谢谢,这解决了我的问题。现在我遇到了其他错误,我将尝试自己解决(或者我将针对 SO 提出具体问题)。
    【解决方案2】:

    或者第二种方式声明另一个首字母缩写词,或者无论如何删除它:

    inflections.rb

    ActiveSupport::Inflector.inflections(:en) do |inflect|
       inflect.acronym 'Api'
    end
    

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2020-04-04
      • 1970-01-01
      相关资源
      最近更新 更多