在Ruby哈希中提取`Moped :: BSON :: Document`属性
在Mongoid 3.0.21中,如何将所有模型的属性作为纯Ruby Hash
?
调用#attributes
或#raw_attributes
返回Moped::BSON::Document
。 虽然它实际上扩展了Hash
, 几个哈希方法不能按预期工作。 特别是 。 #except
返回未修改的self
,而不是散列给定键的hash
更新 : Moped::BSON::Document
正确inheritance了Hash
行为。 我试图用符号命名属性,而不是字符串,这就是为什么#except
不起作用的原因。 不久:做except('pictures')
, except(:pictures)
。
Hash[e.attributes]
其中e是您的模型实例
我为撞到这么老的东西而道歉,但是我想把这个留给我自己以及遇到同样问题的所有未来的人。 我正在使用Mongoid ORM for Rails,它在内部使用Moped来与MongoDB进行交互。
这个gem现在节省了我手动将东西转换为Hash
或HashWithIndifferentAccess
小时HashWithIndifferentAccess
: https : //github.com/mindscratch/mongoid-indifferent-access 。
从本质上讲,它似乎有某种预返回钩子,可以自动将来自MongoDB的所有文件转换为HashWithIndifferentAccess
类型。
不寻找这个点。 只是想把它留在这里,因为它是这个问题的谷歌最高结果,它让我免于疯狂。