簡體   English   中英

如何將ActiveModel :: Serializer應用於自定義對象?

[英]How to apply ActiveModel::Serializer to a custom object?

如果我指定ActiveModel對象的簡單數組,則序列化程序可以工作:

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

但是我需要使用其他字段(例如parent_id等)來響應JSON。

{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

暫無
暫無

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

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