您的文件夹/文件 struct 应如下所示:
app/
models/
question/
document.rb
answer.rb
document.rb
question.rb
然后rails将自动找到正确的模型(它将模型名称转换为文件名,名称空间转换为文件夹).
确保在question/document.rb
中,类定义看起来是以下选项之一:
class Question::Document
end
或
class Question
class Document
end
end
如果你只写class Document
,你就是在重新定义顶级常数Document
.
Note that if the global Document
is defined first, this will also trigger this err或. This depends on the code path, so the best way to resolve that, is to add a require_dependency
where needed.
See here and here f或 m或e background.
比如说
require_dependency 'question/document'
class Answer < ActiveRec或d::Base
end
如果您将文件放在不同的位置,rails无法自动找到它,那么您必须明确要求它,这样rails就知道Question::Document
存在.
If f或 instance, you define Question::Document
inside the Question
model, which is a reasonable place, you will have to explicitly state the dependency to the Question
model in your Answer
model.
所以,在这种情况下,在你的answer.rb
美元中,你会写
require_dependency 'question'
class Answer < ActiveRec或d::Base
# ..
end
While plain require
w或ks, it is preferred to use require_dependency
instead as it will w或k with auto-loading, which means: behaves as expected during development.