ActiveModel Rails serializers provide non-null attributes

I want to use a serializer that displays non-null attributes

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

Is it possible.

Many thanks.

Decision:

  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 
+7
ruby-on-rails serialization notnull attributes
source share
4 answers

From version 0.10.x from the active_model_serializer gem, you must override the serializable_hash method 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 
+11
source share

Thanks to Nabila Hamdaoui for your decision. I made it a bit more reusable with 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 

Using:

swimlane_serializer.rb

 class SwimlaneSerializer < ActiveModel::Serializer include NullAttributesRemover attributes :id, :name, :wipMaxLimit end 
+8
source share
 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 
0
source share

Add validation confirmation: true in your Person model for attributes (: id ,: name ,: phone ,: address ,: email), so when rendering you will get an invalid JSON value.

-2
source share

All Articles