Rails ActiveModel Serializers render not null attributes

9.7k views Asked by At

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
4

There are 4 answers

4
Mehul Gurjar On

Please add validation presence:true in your Person model for (:id, :name, :phone, :address, :email) attributes, so you will get not null JSON value while you render.

1
Andrea Salicetti On

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
4
yaru On

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
0
eugene_trebin On
class ActiveModel::Serializer
  def attributes
    filter(self.class._attributes.dup).each_with_object({}) do |name, hash|
      val = send(name)
      hash[name] = val unless val.nil?
    end
  end
end