使用 ActiveModel Serializer 生成嵌套响应的最佳实践

Best practice when using ActiveModel Serializer to generate nested responses

这是生成具有嵌套键的响应的唯一方法吗?

module Api
  module V20150315
    class ProductConfigurationSerializer < ActiveModel::Serializer
      cached
      delegate :cache_key, to: :object

      embed :ids, include: true

      attributes :id, :short_code, :rank

      has_many :delivery_product_configurations,
        serializer: Api::V20150315::DeliveryProductConfigurationSerializer

    end
  end
end

has_many 是一个序列化程序,它本身调用另一个序列化程序。这样做的最好方法是正确的吗?

是否有其他方法可以做到这一点?这是最语义化的方式吗?

-杰夫

这是 documentation 中指出的正确方法。

如果 delivery_product_configurations 已经定义了序列化程序,则无需指定序列化程序。您可以这样重构:

...
attributes :id, :short_code, :rank

has_many :delivery_product_configurations
...