Mehul Kar

October 01, 2014

Active Model Serializers has_many association

programming

I always forget all the different ways of serializing associations things, so putting down notes:

has_many

class AuthorSerializer < ActiveModel::Serializer
  has_many :posts
emd

This will embed a array of post records into the author record.

{
  "authors": {
    "posts": []
  }
}

has_many, embed :ids

class AuthorSerializer < ActiveModel::Serializer
  has_many :posts, embed: :ids
emd

This will embed post_ids and sideload the posts:

{
  "posts": [],
  "authors": {
    "post_ids": []
  }
}

attribute

class AuthorSerializer < ActiveModel::Serializer
  attributes :post_ids
emd

This will only embed the post_ids.

{
  "authors": {
    "post_ids": []
  }
}