Search code examples
ruby-on-railsjsonruby-on-rails-4activemodelactive-model-serializers

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


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

Solution

  • 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