简体   繁体   English

Rails NameError:初始加载时未初始化的常量

[英]Rails NameError: uninitialized constant on initial load

I have a weird recurring error: every time a worker is booted, it fails on the first attempt and then will work from there on. 我有一个奇怪的重复错误:每次启动工作程序时,它在第一次尝试时都会失败,然后从那里开始工作。 Each time I get the same error. 每次我得到相同的错误。

NameError: uninitialized constant Models::ScorecardVirtualAttributes::LevelCalculator

So I ran through the usual checks: first I checked to see if it was spelt right. 因此,我进行了通常的检查:首先,我检查了它的拼写是否正确。 Then I checked to see if it was dependent on a gem that was not included somehow, which it is not. 然后,我检查了它是否依赖于某种不包含的宝石,事实并非如此。

I think I have replicated the failure in the console. 我想我已经在控制台中复制了故障。 On the initial boot up of the console I run this: 在控制台的初始启动中,我运行以下命令:

[1] toolkit »  defined? Models::ScorecardVirtualAttributes::LevelCalculator
  => nil
[2] toolkit »  defined? ::Models::ScorecardVirtualAttributes::LevelCalculator
  => nil
[3] toolkit »  Models::ScorecardVirtualAttributes::LevelCalculator
  => Models::ScorecardVirtualAttributes::LevelCalculator < Object
[4] toolkit »  defined? ::Models::ScorecardVirtualAttributes::LevelCalculator
  => "constant"

As you can see, when I check to see if it is defined it fails initially. 如您所见,当我检查是否已定义它时,它最初会失败。 But then after calling it directly it returns the expected "constant" when I check to see if it is defined. 但是然后在直接调用它之后,当我检查是否已定义它时,它将返回预期的“常量”。

I then thought that perhaps it's not being loaded correctly. 然后,我认为可能未正确加载。 Here's what I have in my config/application.rb : 这是我的config/application.rb

# Within config/application.rb
...
config.autoload_paths += %W( #{Rails.root}/lib) #/models

I have the lib/models directory added to the autoload_paths , and the model that doesn't seem to be loading initially is in lib/models/scorecards_virtual_attributes/level_calculator.rb . 我将lib/models目录添加到autoload_paths ,并且最初似乎未加载的lib/models/scorecards_virtual_attributes/level_calculator.rb位于lib/models/scorecards_virtual_attributes/level_calculator.rb

Is there perhaps something else that could cause this? 可能还有其他原因可能导致这种情况吗? Or is there something wrong with what I am doing? 还是我的工作有问题?

Rails 3 doesn't autoload files under the lib directory itself. Rails 3不会自动加载lib目录本身下的文件。 If you are using Rails 3 or above, you will have to load it in config/application.rb. 如果您使用的是Rails 3或更高版本,则必须将其加载到config / application.rb中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM