0

Using ActiveModel::Serializer (0.10.0.rc3) using the json-api adapter, how can I render relationships with id only by default?

Consider my serializer

class ASerializer < Api::V1::BaseSerializer
  attributes :id, :name
  has_many :bs
end

However, that renders all the attributes defined in BSerializer, too. I could define a BMiniSerializer to only render the id, and use it as has_many :bs, serializer: BMiniSerializer, but that means I'd have to do it for all Models and add it to all Serializers. Is there a more elegant, default way?

Edit

I suppose this is what :include and :fields are for. Unfortunately it seems that -- since I'm using a different namespace for my API-controllers and serializers from my model I need to specify the serializers for the associated models explicitly for :include and :fields to work.

zeeMonkeez
  • 5,057
  • 3
  • 33
  • 56

1 Answers1

2

Let me show it on the example of Order and OrderItem classes. I also assume we are using version 0.10.0.rc3, because in 0.9.x it works another way.

You should customize your json by passing parameters to serializer. For instance:

render json: @orders, short: true

Parameter :short can be accessed in initializer of OrderSerializer now:

def initialize(object, options = {})
  @short = options[:short]
  super
end

we save this parameter as @short instance variable. Now we can define order_items function, which will include only ids when called with short: true:

def order_items
  if @short
    object.order_items.map{|x| [:id,x.id]}.to_h
  else
    object.order_items
  end
end
dimakura
  • 7,575
  • 17
  • 36
  • I have not tried this approach yet, but it seems it would be cumbersome for a function like `order_items` would have to be defined for every association and every model? Or is that inheritable somehow? – zeeMonkeez Sep 27 '15 at 21:46