在 sinatra 上使用 mongoid ,模型继承导致“未初始化常量”模型名称(父类)

发布于 2024-12-20 09:59:08 字数 730 浏览 5 评论 0原文

我在 Sinatra 上使用 Mongoid 。我用来

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

加载 mongoid 模型文件。

我尝试添加从 A 继承的模型 B ,例如:

models/a.rb:

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

models/b.rb

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

但当我执行应用程序时,出现错误:

uninitialized constant A (NameError)

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

require A

它可以通过在模型 B 的顶部

,但我认为这可能不是解决它的好方法。那么,还有其他方法可以解决这个问题吗?


问候

I'm using Mongoid on Sinatra . And I use

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

to load mongoid model files.

I tried to add a model B inherit from A ,like:

models/a.rb:

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

models/b.rb

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

But when I exec the App , I got errors :

uninitialized constant A (NameError)

So I'm trying to find a solution for this,
it could be fixed by add:

require A

at the top of model B , But I think it may not be a good way to solve it.

So , is there anyother way to fix this??


Regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

め七分饶幸 2024-12-27 09:59:08

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

Sinatra 没有像 Rails 那样的 auto_load 系统。所以你需要完成你需要的所有要求。

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

You just require your file where you A class is define.

Sinatra has no auto_load system like rails have. So you need doing all of your require needed.

require 'a'
class B < A
  field :title , type: String
  field :body , type: String
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文