11

我想使用呈现非空属性的序列化程序

     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

4 回答 4

17

从 gem 的 0.10.x 版本开始active_model_serializer您必须重写该方法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
于 2016-07-20T11:01:27.017 回答
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

用法:

泳道序列化器.rb

class SwimlaneSerializer < ActiveModel::Serializer
  include NullAttributesRemover
  attributes :id, :name, :wipMaxLimit
end
于 2015-05-16T15:54:20.853 回答
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
于 2016-03-28T21:21:02.487 回答
-4

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

于 2014-11-27T09:58:05.477 回答