Oct 2, 2014

Active Model Serializers has_many association

#programming #rails

~ views | ~ words

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": []
  }
}

If you like this post, please share it on Twitter and/or subscribe to my RSS feed. Or don't, that's also ok.