Issues with Active Model Serializers

May 21st, 2015 - Bonn

The ActiveModel::Serializer gives you a nice DSL to handle attributes and relationships when serializing objects.

I had some issues when trying to embed those relationships, in some cases I would just get a hash with the object attributes (probably the same as calling to_json directly) instead of going through the serializer of the associated model.

I found related open issues:

each_serializer options seems not to work (…) insead of specified serializer, it just returns serialised object.

No Matter What I do I only get a normal object hash

I tried many things without success, at the end I got this pattern working at least for the version 0.10.0.pre. It’s ugly but it can be easily replaced in the future when this is no longer an issue

instead of a has_many :attachments, I would add this method:

def attachments
  attachments = object.attachments.to_a
  return [] if attachments.empty?
  serializer =, each_serializer:AttachmentSerializer)[:attachments]

for a belongs_to :category, I would do

def category
  if object.category
    serializer =[:categories]