如何通过对象参数为 ActiveModel Serializer 定义自定义属性?

How to define custom attributes for ActiveModel Serializer by object params?

我有以下序列化器class:

class BooksSerializer < ActiveModel::Serializer
  attributes :name, :position
  attributes :pages unless object.children.present?

但它因错误 "undefined method `object' for SectionSerializer:Class" 而倒下。如何获得这些条件的对象参数?

我只能在函数内部访问对象。例如:

def pages
  object.pages  ....
end

但是我需要根据条件从序列化中排除一些字段。

我找到了解决方案:

class BooksSerializer < ActiveModel::Serializer
  attributes :name
  def attributes(*args)
      hash = super
      hash[:pages] = pages unless object.children.present?          
      hash
  end

  def pages
   ....
  end
  ....
end

这是一个更新的解决方案:

class BooksSerializer < ActiveModel::Serializer
  attributes :name
  attribute :pages, if: -> { object.children.present? }

  def pages
    ...
  end
end