ruby-on-rails – Rails ActiveModel Serializers渲染非null属性
发布时间:2020-12-16 22:47:14 所属栏目:百科 来源:网络整理
导读:我想使用一个渲染非null属性的序列化程序 class PersonSerializer ActiveModel::Serializer attributes :id,:name,:phone,:address,:email end 这可能吗. 非常感谢. 解: class PersonSerializer ActiveModel::Serializer attributes :id,:email def attribu
我想使用一个渲染非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 解决方法
从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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |