【问题标题】:Unable to autoload constant API Controller in Rails 4无法在 Rails 4 中自动加载常量 API 控制器
【发布时间】:2016-09-03 08:30:06
【问题描述】:

我正在我的 Rails 4.2.6 应用程序中创建一个简单的 api 端点,但遇到了问题。

当我点击网址时:http://lvh.me:9077/api/v1/grubs 我收到以下错误:

Unable to autoload constant Api::V1::GrubsController, expected /Users/shakycode/code/grubs/app/controllers/api/v1/grubs_controller.rb to define it

这是我定义端点的 routes.rb 文件。

namespace :api do
    namespace :v1 do
      resources :grubs, only: [:index]
    end
  end

这是我的 app/controllers/api/v1/grubs_controller.rb

class API::V1::GrubsController < ApplicationController
   protect_from_forgery with: :null_session
   before_action :destroy_session

 def destroy_session
   request.session_options[:skip] = true
 end

  def index
    @grubs = Grub.all
    respond_to do |format|
      format.json { render json: @grubs}
    end
  end
end

我有一个使用相同策略的 Rails 4.2.1 应用程序,但在 4.2.6 中,当我尝试拉取 API 时出现此错误。

提前致谢!

更新:这是在浏览器中使用 better_errors 引发的异常:

load_missing_constantactivesupport (4.2.6) lib/active_support/dependencies.rb
490
491
492
493
494
495
496
497
498
499
500
        if loading.include?(expanded)
          raise "Circular dependency detected while autoloading constant #{qualified_name}"
        else
          require_or_load(expanded, qualified_name)
          raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
          return from_mod.const_get(const_name)
        end
      elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
        return mod
      elsif (parent = from_mod.parent) && parent != from_mod &&

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 api-design


    【解决方案1】:

    Rails 通常只将模块的名字大写。换句话说,Rails 需要命名空间Api::V1::GrubsController,但您将其定义为API::V1::GrubsController

    【讨论】:

    • 这个!它甚至说Unable to autoload constant Api::V1::GrubsController, expected /Users/shakycode/code/grubs/app/controllers/api/v1/grubs_controller.rb to define it。因为grubs_controller.rb 定义的是API::V1::GrubsController,而不是Api::V1::GrubsController
    【解决方案2】:

    你的班级名称是

    class API::V1::GrubsController < ApplicationController
    

    而在您的错误中,它试图寻找Api::V1::GrubsController。把你班级的名字改成Api

    【讨论】:

    • 知道了,我错过了 API vs Api 的那部分。
    【解决方案3】:

    我在使用 rails 6 应用程序时遇到了类似的问题。

    问题是我像往常一样定义了我的控制器

    class ProductsController < ApplicationController
      def index
    end
    

    同时,我已将版本控制添加为 API,这导致了这种命名空间 Api/V1

    我是这样解决的

    我只需要将命名空间添加到控制器类定义中。

    class Api::V1::ProductsController < ApplicationController
      def index
    end
    

    就是这样。

    我希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 2014-05-11
      • 2019-08-19
      • 2020-08-27
      • 2019-03-14
      • 2016-04-18
      • 1970-01-01
      • 2021-02-09
      • 2020-03-31
      相关资源
      最近更新 更多