Skip attributes having nil values when to_json on ActiveRecord

前端 未结 3 880
陌清茗
陌清茗 2021-01-03 10:58

i was wondering if there is any way to just skip attributes having nil values when to_json on ActiveRecord. The default behavior is to include a nil value:

Is there

3条回答
  •  礼貌的吻别
    2021-01-03 11:30

    For any hash array, here is what I usually do considering that any value besides false and nil will be considered true:

    filtered_array = array.select{|k,v| v}
    

    Or the bang alternative:

    array.select!{|k,v| v}
    

    This will NOT work, though, if the values could reliably be the boolean value false.

提交回复
热议问题