Retrieving "Moped :: BSON :: Document" attributes in a Ruby hash

In Mongoid 3.0.21, how to get all model attributes as a simple Ruby Hash ?

Calling either #attributes or #raw_attributes returns Moped::BSON::Document . Although it does extend the Hash , several hash methods do not work as expected. In particular, #except returns an unmodified self , not a hash with the given keys, separable .

Update : Moped::BSON::Document correctly inherits Hash behavior. I tried calling attributes with characters, not strings, so #except didn't work. In short: do except('pictures') , not except(:pictures) .

+4
source share
2 answers
 Hash[e.attributes] 

where e is your model instance

+11
source

I apologize for something getting old, but I wanted to leave it here for myself and for all future people who faced this problem. I use Mongoid ORM for Rails, which uses Moped internally to interact with MongoDB.

Now this gem has saved me from the hours and hours when it is manually converted to Hash or HashWithIndifferentAccess : https://github.com/mindscratch/mongoid-indifferent-access .

Essentially, it seems to have a kind of pre-war hook that automatically converts all documents coming from MongoDB to print HashWithIndifferentAccess .

Do not look for points on this. I just wanted to leave it here, because this is the best Google result for this problem, and it saved me from craziness.

+4
source

All Articles