【问题标题】:Best practice when using ActiveModel Serializer to generate nested responses使用 ActiveModel Serializer 生成嵌套响应时的最佳实践
【发布时间】:2016-03-15 14:10:26
【问题描述】:

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

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 是一个序列化器,它本身调用另一个序列化器。最好的方法是正确的吗?

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

-杰夫

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 active-model-serializers


    【解决方案1】:

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

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

    ...
    attributes :id, :short_code, :rank
    
    has_many :delivery_product_configurations
    ...
    

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2011-07-12
      • 1970-01-01
      • 2019-03-16
      相关资源
      最近更新 更多