I have a lot of optional fields in Mongoid, like:
field :key, type: String
field :element, type: String
field :rect, type: Array
If I return a json of this model with only one of them filled I get null values on all the other fields. How can I remove those fields?
My model has nested attributes, which means null values can be on several levels.
Clarifications:
I need a way to remove null fields from the json representation of a model, including null fields in all nested attributes.
Code Example:
1.9.3-p0 :005 > u=Muse.new(:key=>'ram').to_json
=> "{\"_id\":\"4f1ced749c2ee4219d000003\",\"element\":null,\"key\":\"ram\",\"rect\":null}"
By default
mongoidhas the ability to remove empty fields. If you let some fields empty,mongoidwill removes them on insert.in the below example, I left out the fields element & rect
and it works perfectly. But if you put a nil value in the field
It gets inserted. I assume that’s the exact problem in your code. So you can work around this by converting JSON hash representation using
as_jsonand remove the nil fieldsBut to go to the inner levels, you cannot use
as_json. check the below codeNow you see the field dummy inside the embedded doc house is still with nil. so my best advice is Dont put the nil values in db at all. To do that put a
before_savecallback on your models (embedded too) and remove the empty fields.Also I will show you how to remove nil fields from nested objects too. Use it if there is no other way
We can use
attributesof mongoid model to get the hash representation of the object including the nested levelsand you have to find is there any Hash inside the mongoid object, if one, we have to use the
reject! {|k,v| v.nil?}on that Hash tooto put together all
and call this with attributes of the model,
Thats all. Hope it helps