LoadError无法自动加载常量 [英] LoadError Unable to autoload constant
问题描述
自动加载器似乎正在加载lib/tools/address而不是我的模型
It seems that autoloader is loading up lib/tools/address and not my model
地址抛出以下错误
LoadError:无法自动加载常量地址,应该是预期的 /lib/tools/address.rb进行定义
LoadError: Unable to autoload constant Address, expected /lib/tools/address.rb to define it
有人可以告诉我我在做什么错.我以为
地址将指向常量模型/address.rb
和
工具::指向lib/tools/address.rb的地址
Can someone tell me what I'm doing wrong. I thought that
Address would point to constant models/address.rb
and
Tools::Address to lib/tools/address.rb
app/models/address.rb
app/models/address.rb
class Address
blah
end
lib/tools/address.rb
lib/tools/address.rb
module Tools
class Address
blah blah
end
end
推荐答案
以我的经验,使用具有相同名称但具有不同命名空间的多个常量可能很棘手.在您的情况下,您有两个Address
常量,一个在顶级,另一个在Tools
命名空间内.这可能会使Rails自动加载器感到困惑.
In my experience it can be tricky to use multiple constants with the same name but with different namespaces. In your case you have two Address
constants, one at the top level and another inside the Tools
namespace. This can confuse the Rails autoloader.
一些可能的解决方案:
当您要使用顶级Address
(即您的模型)时,请使用::Address
明确引用它.
When you want to use the top-level Address
(i.e. your model), refer to it explicitly using ::Address
.
如果这不起作用,您还可以使用require_dependency
向自动装带器提示您想要的内容.在为您提供LoadError的文件的顶部,放置以下行:
If that doesn't work, you can also use require_dependency
to give the autoloader a hint of what you want. At the top of the file that is giving you the LoadError, put this line:
require_dependency("address")
以下是文档:
require_dependency
使用机制解释文件,并将其定义的常量标记为自动加载. file_name可以是字符串,也可以是to_path的响应.
Interprets a file using mechanism and marks its defined constants as autoloaded. file_name can be either a string or respond to to_path.
在绝对需要在此点定义某个常量的代码中使用此方法.一个典型的用例是在不同名称空间中对具有相同相对名称的常量进行确定性的常量名称解析,否则它们的求值将取决于加载顺序.
Use this method in code that absolutely needs a certain constant to be defined at that point. A typical use case is to make constant name resolution deterministic for constants with the same relative name in different namespaces whose evaluation would depend on load order otherwise.
这篇关于LoadError无法自动加载常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!