0

I have a couple models. Let's call them Widget and Gadget.

My #index for for Widget and Gadget looks something like this

def index
    widgets = Widget.all
    if widgets
        respond_with widgets, each_serializer: Api::V1::WidgetSerializer
    else
        render json: { message: [t(:not_found_widget)] }, status: :not_found
    end
end     

def index
    gadgets = Gadget.all
    if gadgets
        respond_with gadgets, each_serializer: Api::V1::GadgetSerializer
    else
        render json: { message: [t(:not_found_gadget)] }, status: :not_found
    end
end 

And my serializers...

class Api::V1::WidgetSerializer < ActiveModel::Serializer
  attributes :id, :desc
end

 class Api::V1::GadgetSerializer < ActiveModel::Serializer
  attributes :id, :desc
end

However, I have the need for a resource that returns both of those in 1. I need both widgets and gadgets returned at once. So the json would look like...

{
    "widgets": [
        {
            "id": 1,
            "desc": "One"
        },
        {
            "id": 2,
            "desc": "Two"
        }
    ],
    "gadgets": [
        {
            "id": 1,
            "desc": "One"
        },
        {
            "id": 2,
            "desc": "Two"
        }
    ]
}

How can I achieve this. Something like

widgets = Widget.all
gadgets = Gadget.all
respond_with widgets, each_serializer: Api::V1::WidgetSerializer, gadgets, each_serializer: Api::V1::GadgetSerializer

However, this clearly doesn't work.

chris P
  • 6,359
  • 11
  • 40
  • 84

2 Answers2

3

Serializer classes don't have to match AR models. Serializer classes should be used as your representation of your JSON you want to produce. In your example, let's assume to call a new serializer DashboardSerializer, then you can put both widgets and gadgets there:

class DashboardSerializer < ActiveModel::Serializer
  self.root = false

  attributes :widgets, :gadgets

  def widgets
    Widget.all
  end

  def gadgets
    Gadget.all
  end
end
Samnang
  • 5,536
  • 6
  • 35
  • 47
0

The only way I can see this working is if you had a model that has_many widgets and has_many gadgets with it's own serializer as AMS will apply the correct serializers to associations declared in a serializer.

something like

class Composite < ActiveRecord::Base
 has_many :widgets
 has_many :gadgets
end

class CompositeSerializer < ActiveModel::Serializer
  attributes :id
  has_many :widgets
  has_many :gadgets
end
errata
  • 23,596
  • 2
  • 22
  • 32
  • Is there a way to build a large json string manually of all the objects I want and return that? (Preferably minus the timestamps) – chris P May 31 '15 at 15:31