Rails ActiveModel Serializers render not null attributes

Nabila Hamdaoui picture Nabila Hamdaoui · Nov 27, 2014 · Viewed 7.9k times · Source

I want to use a serializer that renders not null attributes

     class PersonSerializer < ActiveModel::Serializer
        attributes :id, :name, :phone, :address, :email
     end

Is this possible.

Many thanks.

Solution:

 class PersonSerializer < ActiveModel::Serializer
    attributes :id, :name, :phone, :address, :email
    def attributes
     hash = super
     hash.each {|key, value|
      if value.nil?
      hash.delete(key)
     end
    }
    hash
   end
  end

Answer

Andrea Salicetti picture Andrea Salicetti · Jul 20, 2016

From version 0.10.x of active_model_serializer gem, you have to override the method serializable_hash instead of attributes:

# place this method inside NullAttributesRemover or directly inside serializer class
def serializable_hash(adapter_options = nil, options = {}, adapter_instance = self.class.serialization_adapter_instance)
  hash = super
  hash.each { |key, value| hash.delete(key) if value.nil? }
  hash
end