LoadError Unable to autoload constant

十年热恋 提交于 2019-12-23 16:49:44

问题


It seems that autoloader is loading up lib/tools/address and not my model

Address throws the following error

LoadError: Unable to autoload constant Address, expected /lib/tools/address.rb to define it

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

class Address
  blah
end

lib/tools/address.rb

module Tools
  class Address
    blah blah
  end
end

回答1:


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.

Some possible solutions:

When you want to use the top-level Address (i.e. your model), refer to it explicitly using ::Address.

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")

Here's the documentation:

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.



来源:https://stackoverflow.com/questions/39777480/loaderror-unable-to-autoload-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!