2016-09-29 29 views
2

看來,磁帶自動加載機加載了LIB /工具/地址,而不是我的模型LoadError無法自動加載恆

地址引發以下錯誤

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

有人能告訴我,我做錯了什麼。我認爲
地址將指向不變模型/ address.rb

工具::地址到LIB /工具/ address.rb

應用程序/模型/ address.rb

LIB /工具/ address.rb

module Tools 
    class Address 
    blah blah 
    end 
end 
+0

有一個在LIB /工具/ address.rb缺少結束。這只是一個錯字嗎? – jaydel

+0

@jaydel是的,只是一個錯字 – bopritchard

回答

5

在我的經驗,它可能會非常棘手使用多種常量名稱相同,但不同的命名空間。在你的情況下,你有兩個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.

相關問題