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