Skip attributes having nil values when to_json on ActiveRecord

前端 未结 3 881
陌清茗
陌清茗 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:28

    @lars's answer will work for a single object, but for an array of Active Record objects, you will have to iterate through every element of the array and do the conversion. If you want this conversion everytime you call .to_json or render :json => for that model, you can override the as_json function in the model like this:

    class Model
      ..
      def as_json(options={})
        super(options).reject { |k, v| v.nil? }
      end
    end
    

    Also, I am assuming you have defined, ActiveRecord::Base.include_root_in_json = false in the your environment(config/initializers/active_record.rb in Rails 3 and config/initializers/new_rails_defaults.rb in Rails 2). Otherwise, you will have to implement @lars's function fully in the model(taking value[0] to get the attribute hash etc.).

    Use this method only if you want to do this everytime you call .to_json or render :json => for that model. Otherwise you should stick to @lars's answer.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 11:35

    You can get at the Hash representation of an ActiveRecord object used for serializing to JSON through the as_json method.

    The hash will have the (underscored) class name as the only key, and the value will be another hash containing the attributes of the class.

    hash = object.as_json # Convert to hash
    hash.values[0].reject! {|k,v| v.nil?} # Remove attributes with value nil
    hash.to_json # Convert to JSON string
    
    0 讨论(0)
提交回复
热议问题