Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip attributes having nil values when to_json on ActiveRecord

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 an option way to make this value just not appear?

like image 481
Oksana Avatar asked Dec 10 '22 05:12

Oksana


2 Answers

@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.

like image 111
rubyprince Avatar answered May 26 '23 21:05

rubyprince


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
like image 43
Lars Haugseth Avatar answered May 26 '23 21:05

Lars Haugseth