Extract `Moped::BSON::Document` attributes in Ruby hash

泪湿孤枕 提交于 2019-12-22 09:31:32

问题


In Mongoid 3.0.21, how to get all model's attributes as a plain Ruby Hash?

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.

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).


回答1:


Hash[e.attributes]

where e is your model instance




回答2:


I apologize for bumping something so old, but I wanted to leave this here for myself and all the future people who run into this same issue. I am using the Mongoid ORM for Rails, which uses Moped internally for its interaction with MongoDB.

This gem has now saved me hours and hours of manually converting things to Hash or HashWithIndifferentAccess: https://github.com/mindscratch/mongoid-indifferent-access.

Essentially it seems to have some sort of pre-return hook that automatically converts all documents coming from MongoDB to type HashWithIndifferentAccess.

Not looking for points on this. Just wanted to leave this here because it is the top Google result for this issue and it saved me from going insane.



来源:https://stackoverflow.com/questions/15006259/extract-mopedbsondocument-attributes-in-ruby-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!