【问题标题】:LoadError Unable to autoload constant ( Rails Engine )LoadError 无法自动加载常量(Rails 引擎)
【发布时间】:2019-03-14 18:27:00
【问题描述】:

每当我点击由 rails 引擎暴露的端点(例如:greet)时,我都会收到此错误。

错误:

"LoadError(Unable to autoload constant TestingController, 
expected /local_path/app/controllers/testing_controller.rb to define it): 
/Users/xxxxx/.rvm/gems/ruby-2.5.1/gems/activesupport-5.2.1/lib/active_support/
dependencies.rb:507:in `load_missing_constant'"

引擎:

我有一个引擎,其动作方法greet 定义如下

# type: class
# path: app/controllers/testing_controller.rb
# file name: testing_controller.rb 
module Parent
  module Child
    class TestingController < ApplicationController
      def initialize
        @name = 'BOB'
      end

      def greet
        render json: {'hi': 'hi', 'name': @name}
      end
    end
  end
end

路由定义为

# type: route
# path: app/config/routes.rb
# file name: routes.rb 
Parent::Child::Engine.routes.draw do
  get 'greet', to: 'testing#greet', as: :greet
end

详情:

此引擎已安装到 gem ABC,然后在名为 Example 的 rails 应用程序中使用。当我通过应用程序中的greet 路由时 http://localhost:3000/greet 我第一次收到LoadError

但是,如果我刷新它呈现的页面 json 符合预期。 {"hi":"hi","name":"BOB"}

我们有development.rb (app/config/env/) 有缓存和急切负载定义如下

config.cache_classes = false
config.eager_load = false

红宝石:2.5.1
导轨:5.2.1

感谢您的帮助,非常感谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rubygems ruby-on-rails-5 rails-engines


    【解决方案1】:

    该消息似乎来自预期,即在文件testing_controller.rb 的根级别中有一个TestingController 类的定义,而您将该类定义为嵌套在Parent::Child:: 模块中。

    我猜如果你把你的testing_controller.rb 文件放在以下路径:app/controllers/parent/child/testing_controller.rb 错误就会消失。

    【讨论】:

    • 成功了。我希望错误像您在此处指出的那样清楚。谢谢
    猜你喜欢
    • 2020-08-27
    • 2019-08-19
    • 1970-01-01
    • 2016-04-13
    • 2020-03-31
    • 1970-01-01
    • 2017-10-22
    • 2014-05-11
    • 2016-04-18
    相关资源
    最近更新 更多