在Ruby哈希中提取`Moped :: BSON :: Document`属性 [英] Extract `Moped::BSON::Document` attributes in Ruby hash
问题描述
在Mongoid 3.0.21中,如何以纯Ruby Hash
的形式获取所有模型的属性?
In Mongoid 3.0.21, how to get all model's attributes as a plain Ruby Hash
?
调用#attributes
或#raw_attributes
会返回Moped::BSON::Document
.尽管它实际上扩展了Hash
,但是几个哈希方法无法按预期工作.尤其是.#except
返回未经修改的self
,而不是在剥离给定键的情况下进行散列
Calling either #attributes
or #raw_attributes
returns Moped::BSON::Document
. While it actually extends Hash
, several hash method does not work as expected. Particularly .#except
returns unmodified self
, not hash with given keys stripped off
更新:Moped::BSON::Document
正确继承了Hash
的行为.我试图用符号而不是字符串来命名属性,这就是为什么#except
无法正常工作的原因.很快:执行except('pictures')
,而不是except(:pictures)
.
Update: Moped::BSON::Document
properly inherits behavior of Hash
. I was trying to name attributes with symbols, not strings, that's why #except
didn't work. Shortly: do except('pictures')
, not except(:pictures)
.
推荐答案
Hash[e.attributes]
其中e是您的模型实例
这篇关于在Ruby哈希中提取`Moped :: BSON :: Document`属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!