ActiveModel::Serializer定义属性属性?

ActiveModel::Serializer define attribute attributes?

我正在尝试为我的 Rails 应用实现 JSON API。它需要定义 attributes 字段。但是 ActiveModel::Serializer 有一个同名的方法,因此

class FooSerializer < ActiveModel::Serializer
  attributes :attributes

  def attributes
    {
      # to be filled
    }
  end
end

只会重写原来的方法。是否有可能以某种方式添加 attributes 字段?

ActiveModel Serializer 支持开箱即用的 JSON API。您只需要设置合适的适配器。

ActiveModelSerializers.config.adapter = :json_api

https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/adapters.md

操作方法如下:

class FooSerializer < ActiveModel::Serializer
  def attributes(*args)
    hash = super
    hash[:attributes] = attributes_list
    hash
  end

  def attributes_list
    {
      # to be filled
    }
  end
end