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)
.
Hash[e.attributes]
where e is your model instance
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With