似乎自动加载器正在加载 lib/tools/address 而不是我的模型
地址抛出以下错误
LoadError: Unable to autoload constant Address, expected /lib/tools/address.rb to define it
有人可以告诉我我做错了什么吗?我以为
地址将指向常量 models/address.rb
和
工具::lib/tools/address.rb 的地址
应用程序/模型/地址.rb
class Address
blah
end
lib/tools/address.rb
module Tools
class Address
blah blah
end
end
最佳答案
根据我的经验,使用具有相同名称但具有不同命名空间的多个常量可能会很棘手。在您的情况下,您有两个 Address
常量,一个位于顶层,另一个位于 Tools
命名空间内。这可能会使 Rails 自动加载器感到困惑。
一些可能的解决方案:
当您想使用顶级Address
(即您的模型)时,请使用::Address
显式引用它。
如果这不起作用,您还可以使用 require_dependency
向自动加载器提示您想要什么。在出现 LoadError 的文件顶部,输入以下行:
require_dependency("address")
这是文档:
require_dependency
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.
关于ruby-on-rails - LoadError 无法自动加载常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39777480/