Skip attributes having nil values when to_json on ActiveRecord

前端 未结 3 902
陌清茗
陌清茗 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.

提交回复
热议问题