Mongoid:向模型添加了哈希,但无法写入

发布于 2024-12-26 21:54:41 字数 532 浏览 0 评论 0原文

我有一个模型,实体。

class Entity
  include Mongoid::Document

  field :x
  field :y
  field :z, type => Hash, :default => {} # new field

end

我向其中添加了一个新字段,即哈希值。当我尝试使用它时,出现错误。我的代码是:

e = Entity.first
if e.z["a"] # if there is a key of this in it?
  e.z["a"] = e.z["a"] + 1
else
  e.z["a"] = 1
end

但是,这个错误与未定义的方法获取哈希有关。如果我尝试为其创建一个初始值设定项,以在现有文档中设置值,则会出现相同的错误。我做错了什么?

初始化器看起来像:

e = Entity.first
e.write_attribute(:z, {})

谢谢

I've got a model, Entity.

class Entity
  include Mongoid::Document

  field :x
  field :y
  field :z, type => Hash, :default => {} # new field

end

I added a new field to it, a hash. When I try to use it, I get an error. My code is:

e = Entity.first
if e.z["a"] # if there is a key of this in it?
  e.z["a"] = e.z["a"] + 1
else
  e.z["a"] = 1
end

But, this error with an undefined method get for hash. If I try to create an initializer for it, to set the values in an existing document, it errors with the same error. What am I doing wrong?

Initializer looks like:

e = Entity.first
e.write_attribute(:z, {})

Thanks

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

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

发布评论

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

评论(1

鹿童谣 2025-01-02 21:54:41

排序了。

看来答案是在 Mongoid 1.9.5 中将哈希设置为:

field :hash_field, :type => Hash, :default => Hash.new

并且它可以访问并初始化它。不太明白为什么,但很高兴得到答案!

Sorted it.

It seems the answer is to set in Mongoid 1.9.5 the hash to:

field :hash_field, :type => Hash, :default => Hash.new

and it can access and initialize it. Not quite understanding why, but happy to have the answer !

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