在Ruby哈希中提取`Moped :: BSON :: Document`属性 [英] Extract `Moped::BSON::Document` attributes in Ruby hash

查看:38
本文介绍了在Ruby哈希中提取`Moped :: BSON :: Document`属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆