Your folder/file structure should look as follows:
app/
models/
question/
document.rb
answer.rb
document.rb
question.rb
And then rails will automatically find the correct models (it will translate the model name to a filename, and namespaces are translated to folders).
Make sure that inside your question/document.rb
the class definition looks as one of the following alternatives:
class Question::Document
end
or
class Question
class Document
end
end
If you write just class Document
you are redefining the toplevel constant Document
.
Note that if the global Document
is defined first, this will also trigger this error. 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 for more background.
E.g. something like
require_dependency 'question/document'
class Answer < ActiveRecord::Base
end
If you put the file in a different place, where rails cannot automatically find it, you will have to explicitly require it, so rails knows Question::Document
exists.
If for 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.
So, in that case, in your answer.rb
you will write
require_dependency 'question'
class Answer < ActiveRecord::Base
# ..
end
While plain require
works, it is preferred to use require_dependency
instead as it will work with auto-loading, which means: behaves as expected during development.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…