簡體   English   中英

使用 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是一個序列化器,它本身調用另一個序列化器。 這樣做的最佳方法是正確的嗎?

有沒有其他方法可以做到這一點? 這是最語義化的方式嗎?

-傑夫

這是文檔中指出的正確方法。

如果delivery_product_configurations已經定義了序列化程序,則不需要為它指定序列化程序。 您可以這樣重構:

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

has_many :delivery_product_configurations
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM