Rails ActiveModel Serializers呈现非null属性

时间:2014-11-27 09:49:01

标签: ruby-on-rails serialization attributes notnull

我想使用渲染非null属性的序列化程序

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

这可能。

非常感谢。

解决方案:

 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 个答案:

答案 0 :(得分:14)

active_model_serializer gem版本 0.10.x ,您必须覆盖方法serializable_hash而不是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

答案 1 :(得分:10)

感谢Nabila Hamdaoui的解决方案。 我通过模块使其更加可重复使用。

<强> 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

用法:

<强> swimlane_serializer.rb

class SwimlaneSerializer < ActiveModel::Serializer
  include NullAttributesRemover
  attributes :id, :name, :wipMaxLimit
end

答案 2 :(得分:0)

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

答案 3 :(得分:-2)

请在您的Person模型中为(:id,:name,:phone,:address,:email)属性添加验证状态:true,这样您在渲染时将获得非空JSON值。