Search code examples
ruby-on-railsrubyruby-on-rails-3active-model-serializers

Best practice when using ActiveModel Serializer to generate nested responses


Is this the only way to generate a response that has nested keys?

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

The has_many is a serializer which itself calls another serializer. Is the best way to do this right?

Are there alternative ways to do this? Is this the most semantic way?

-Jeff


Solution

  • This is the correct way as indicated in the documentation.

    You do not need to specify the serializer for the delivery_product_configurations if it already has a serializer defined. You can refactor thus:

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