2

If I specify simple array of ActiveModel objects serializer works:

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

But I need to respond with JSON with additional fields, such as parent_id, etc.

{parent_id: 15, childs: @childs}

Any idea how to achieve it?

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
yaru
  • 1,260
  • 1
  • 13
  • 29

1 Answers1

2

Yay! I figure it out! Hope it helps someone else!

respond_to do |format|
            format.json { render json:
                { parent_id: parent_id, childs: ActiveModel::ArraySerializer.new(@childs, each_serializer: ItemSerializer) }
            }
        end
yaru
  • 1,260
  • 1
  • 13
  • 29