Mongoid:向模型添加了哈希,但无法写入
我有一个模型,实体。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
排序了。
看来答案是在 Mongoid 1.9.5 中将哈希设置为:
并且它可以访问并初始化它。不太明白为什么,但很高兴得到答案!
Sorted it.
It seems the answer is to set in Mongoid 1.9.5 the hash to:
and it can access and initialize it. Not quite understanding why, but happy to have the answer !