我正在使用命名空间和文件夹在 Rails 中对我的模型进行分组,但遇到了文件未加载和 TypeError - is not a module
的问题。正在抛出错误。
这是跟踪的顶部:
17:06:26 web.1 | TypeError - SetNetsuite is not a module:
17:06:26 web.1 | app/models/integrations/set_netsuite/scenarios/new_mavenlink_project.rb:2:in `<module:Integrations>'
17:06:26 web.1 | app/models/integrations/set_netsuite/scenarios/new_mavenlink_project.rb:1:in `<top (required)>'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/dependencies.rb:443:in `block in load_file'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/dependencies.rb:633:in `new_constants_in'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/dependencies.rb:442:in `load_file'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/dependencies.rb:342:in `require_or_load'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/dependencies.rb:480:in `load_missing_constant'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/dependencies.rb:180:in `const_missing'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/inflector/methods.rb:240:in `block in constantize'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/inflector/methods.rb:236:in `constantize'
17:06:26 web.1 | activesupport (4.1.10) lib/active_support/core_ext/string/inflections.rb:66:in `constantize'
我的代码如下所示:
module Integrations
module SetNetsuite
module Scenarios
class NewProject < Scenario
end
end
end
end
我的文件夹结构是:
- models/
- integrations/
- set_netsuite/
- scenarios/
- new_project.rb
我正在自动加载
/models
中的所有内容:config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
如果我将模型更改为此,它会起作用:
module Integrations
class SetNetsuite::Scenarios::NewProject < Scenario
end
end
我知道命名空间类的行为与嵌套模块略有不同,但我更愿意使用嵌套模块方法。
任何帮助或建议将不胜感激。提前致谢!
最佳答案
UPD
看来你require 'integrations'
以及 new_mavenlink_project.rb
中的所有其他模块,虽然您不应该这样做,但自动加载的重点是您不需要在 rails 应用程序中的任何地方要求任何东西。要访问您的 NewProject 类,您只需调用:
Integrations::SetNetsuite::Scenarios::NewProject
在这种情况下,您不需要向
autoload_paths
添加任何内容。 , rails 将从嵌套中生成它。
关于ruby-on-rails - rails : "is not a module" error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30314784/