我有四种型号(DocumentQuestionQuestion::DocumentAnswer).在我的Answer型号中

validates :text,
  presence: { :unless => Proc.new{ |a| a.question.is_a? Question::Document } }

这给了我警告

warning: toplevel constant Document referenced by Question::Document

如何防止发生此警告(不重命名我的类)?

推荐答案

您的文件夹/文件 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.

Ruby-on-rails相关问答推荐

仅在两个子域间共享Rails cookies,并为所有其他子域使用单独的cookie

使用has_many_through关联创建记录 – Ruby on Rails

使用带有 Paper Trail gem 的子类

CanCanCan、Pagy 和 Meil​​iSearch,如何组合这 3 个 gem?

'elseif' 还存在吗?

如何在 Rails 3 中使用 Capybara 单击具有相同文本的第二个链接?

在 Windows 上使用 Ruby 进行开发

如何在 Ruby on Rails 中的 cookie 上设置 HttpOnly 标志

Rails data-disable-with re-enable 按钮

什么是Ruby 用于 BESIDES 轨道?

在 where 查询中查找 nil has_one 关联

如何将自定义路由添加到资源路由

Rspec 与 TestUnit

Rails Activeadmin - 自定义关联 Select 框

Ruby 和 Ruby on Rails 离线 API 文档

连接表的最佳 SQL 索引

在rails中带有内部文本或html的link_to image_tag

Post.all.map(&:id) 是什么意思?

在创建控制器和模型之后(仅)创建 Ruby on Rails 视图

资源和资源方法之间的区别