Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveModel Serializers render not null attributes

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
like image 533
Nabila Hamdaoui Avatar asked Nov 27 '14 09:11

Nabila Hamdaoui


2 Answers

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
like image 171
Andrea Salicetti Avatar answered Nov 01 '22 11:11

Andrea Salicetti


Thanks Nabila Hamdaoui for your solution. I made it a little more reusable via modules.

null_attribute_remover.rb

module NullAttributesRemover
  def attributes
    hash = super
    hash.each do |key, value|
      if value.nil?
        hash.delete(key)
      end
    end
    hash
  end
end

Usage:

swimlane_serializer.rb

class SwimlaneSerializer < ActiveModel::Serializer
  include NullAttributesRemover
  attributes :id, :name, :wipMaxLimit
end
like image 23
yaru Avatar answered Nov 01 '22 10:11

yaru