如何将 ActiveModel::Serializer 应用于自定义对象?

How to apply ActiveModel::Serializer to a custom object?

如果我指定简单的 ActiveModel 对象数组序列化器工作:

format.json { render json: @childs, each_serializer: ItemSerializer }

但我需要用 JSON 回复额外的字段,例如 parent_id

{parent_id: 15, childs: @childs}

知道如何实现吗?

item_serializer.rb

class ItemSerializer < ActiveModel::Serializer
  attributes :id, :name, :parent_id
end

items_controller.rb

 def roots
    @childs = Item.where(parent_id: 15)
    respond_to do |format|
        # serializer below does not work...
        format.json { render json: {parent_id: 15, childs: @childs}, each_serializer: ItemSerializer }
    end
end

耶!我想通了!希望对其他人有帮助!

respond_to do |format|
            format.json { render json:
                { parent_id: parent_id, childs: ActiveModel::ArraySerializer.new(@childs, each_serializer: ItemSerializer) }
            }
        end