如果 rails 的子文件夹中有 class,为什么我会收到未初始化的常量错误?

Why am i getting Uninitialized constant error if class in subfolder in rails?

我遇到了一个困扰我的奇怪问题。我在 /lib/**/** 中定义了一些自定义 classes,我正试图将其加载到控制器中。所以给出:


# dir: lib/forms/enums/data_type.rb
module Forms
  class DataType
    TEXT       = 0
    NUMBER     = 1
  end
end


# dir: controllers/form_controller.rb
class FormController < ApplicationController
  def update
   # Here, I get the uninitialized constant error for MyModule::DataType
   if params[:someAttr] ===  Forms::DataType::TEXT
    ...
   end
  ...
  end
...
end

但是,如果我将 DataType class 放在目录中:lib/forms/,即与 forms 相同的文件夹,而不是子文件夹 enums ,它可以很好地引用它。

我确定我在做一些基本的非常错误的事情,但我不明白为什么 Rails 可以在模块下找到任何 classes,但不能在子目录中找到?

Update/Edit:如果我引用它似乎可以工作,将它添加到一个额外的子模块下,并将其引用为 Forms::Enums::DataType::TEXT,如下所示:


# dir: lib/forms/enums/data_type.rb
module Forms
  module Enums
    class DataType
      TEXT       = 0
      NUMBER     = 1
    end
  end
end

那么,如果我引入子目录,是不是一定要引入子模块?

看起来 - 正如对问题本身的评论所指出的,

  1. 如果我引入一个子目录,如果你需要自动加载,好像需要一个子模块。
  2. 如果你手动加载一个class
  3. ,你可以绕过这个