Rails ActiveModel Serializers呈现非null属性

Nab*_*oui 10 serialization attributes ruby-on-rails notnull

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

     class PersonSerializer < ActiveModel::Serializer
        attributes :id, :name, :phone, :address, :email
     end
Run Code Online (Sandbox Code Playgroud)

这可能吗.

非常感谢.

解:

 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
Run Code Online (Sandbox Code Playgroud)

And*_*tti 15

从版本0.10.xactive_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
Run Code Online (Sandbox Code Playgroud)


yar*_*aru 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
Run Code Online (Sandbox Code Playgroud)

用法:

swimlane_serializer.rb

class SwimlaneSerializer < ActiveModel::Serializer
  include NullAttributesRemover
  attributes :id, :name, :wipMaxLimit
end
Run Code Online (Sandbox Code Playgroud)

  • 我把它写成:`super.keep_if {| _,value | value.present?}` (2认同)
  • 甚至更短:`super.compact` (2认同)

小智 -4

请在您的 Person 模型中为 (:id、:name、:phone、:address、:email) 属性添加验证存在:true,这样您在渲染时不会得到 null JSON 值。