Rails:控制器无法从 module/namespace 识别 class - 未初始化的常量

Rails: controller cannot recognize class from module/namespace - uninitialized constant

我已经为 API 逻辑创建了目录:app/api/EtherumAPI/V1 并将以下代码放在那里:

module EtherumAPI
    module V1
        class Request


            class << self
                def trancation
                end 
            end
        end 
    end
end

在我的 application.rb 中注册:

config.autoload_paths << "#{Rails.root}/app/api"
config.eager_load_paths << "#{Rails.root}/app/api"

并尝试在我的控制器中调用它:

  def index
    @test = EtherumAPI::V1::Request
    @test.trancation
  end

但是我得到了这个错误:

uninitialized constant HomeController::EtherumAPI

我也试过 "include EtherumAPI::V1" 之类的方法,但也没有成功。我该如何修复它并能够从 Request class?

调用方法

首先你可以摆脱:

config.autoload_paths << "#{Rails.root}/app/api"
config.eager_load_paths << "#{Rails.root}/app/api"

app 的所有子目录默认为自动加载路径。有时,自动加载器会得到 "stuck" 并且不会拾取新添加的目录。您通常可以通过重新启动 rails 服务器和 spring ($ spring stop) 来解决这个问题。

这里有两个问题。第一个是拐点。 Rails 通过驼峰化 class 名称来改变 classes 中的文件名。不幸的是,这对于首字母缩写词如 ABC -> a_b_c.rb 不会自动起作用。

因此,为了让自动加载器在 etherum_api.rb 中查找 EtherumAPI,您需要添加一个变形:

# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'EtherumAPI'
end

第二个问题是模块名称必须与文件的实际路径匹配。

# app/api/etherum_api/v1/request.rb
module EtherumAPI
    module V1
        class Request
            class << self
                def trancation
                end 
            end
        end 
    end
end