ruby-on-rails – Rails ActiveModel Serializers渲染非null属性

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails ActiveModel Serializers渲染非null属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用一个渲染非null属性的序列化程序
class PersonSerializer < ActiveModel::Serializer
        attributes :id,:name,:phone,:address,:email
     end

这可能吗.

非常感谢.

解:

class PersonSerializer < ActiveModel::Serializer
    attributes :id,:email
    def attributes
     hash = super
     hash.each {|key,value|
      if value.nil?
      hash.delete(key)
     end
    }
    hash
   end
  end

@R_403_323@

从active_model_serializer gem的0.10.x版本开始,您必须覆盖方法serializable_hash而不是属性
# 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
原文链接:https://www.f2er.com/ruby/265545.html

猜你在找的Ruby相关文章