【问题标题】:using mongoid on sinatra , model inheritance causing "uninitialized constant" modelname (parent class)在 sinatra 上使用 mongoid,模型继承导致“未初始化的常量”模型名(父类)
【发布时间】:2011-12-08 09:04:41
【问题描述】:

我在 Sinatra 上使用 Mongoid。我用

Dir.glob(File.join(File.dirname(__FILE__),'models','*.rb')).each do |file|
  require file
end

加载 mongoid 模型文件。

我尝试添加一个模型 B 继承自 A ,例如:

模型/a.rb:

class A
  include Mongoid::Document
  include Mongoid::Timestamps
  field :custom_id, type: Integer
end

模型/b.rb

class B < A
  field :title , type: String
  field :body , type: String
end

但是当我执行应用程序时,我得到了错误:

uninitialized constant A (NameError)

所以我正在尝试为此找到解决方案, 它可以通过添加来修复:

require A

在模型 B 的顶部,但我认为这可能不是解决它的好方法。

那么,有没有其他方法可以解决这个问题?


问候

【问题讨论】:

  • require 行添加到依赖于其他文件的文件没有任何问题,只要确保加载顺序正确即可。不过,在您的情况下,您可能想做一个require 'a',或者甚至需要更具体地了解命名空间。

标签: sinatra mongoid


【解决方案1】:

您只需要定义 A 类的文件。

Sinatra 没有像 rails 那样的 auto_load 系统。所以你需要做所有你需要的。

require 'a'
class B < A
  field :title , type: String
  field :body , type: String
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    相关资源
    最近更新 更多