I’m using MongoDB but I’m not really using it’s dynamic fields capabilities
field :fb_followers => Integer
field :twitter_followers => Integer
field :twitter_rts => Integer
field :link_visiting => Integer
field :reduce_points_per_day => Integer
How do I write this so each of those fields is optional for the model?
So here’s some Mongoid-specific information. First of all, make sure
allow_dynamic_fieldsis set totruein your configuration (it defaults totrue, but always good to be sure).Here’s the world’s simplest Mongoid class, for my examples:
So, we can of course set our
static_fieldnormally:But we can’t do a dynamic field “on the fly” because Mongoid doesn’t know about it yet.
However, I can use
write_attributeto write a dynamic field:And, now that I’ve “created” that field in Mongoid, I can now use the regular mechanism for accessing a field, even though it’s not in my class definition:
Also, note that if you load a Mongoid document with non-Mongoid-specified fields, you can indeed access them the same way:
However, the safest way to work with dynamic fields is using
write_attributeandread_attribute(or their shortcuts,[]=and[]) as these won’t throwNoMethodErrors if the field doesn’t exist.Hope that helps. It’s really pretty simple when you get used to it. For more info, see: http://mongoid.org/docs/documents/dynamic.html