Skip to content

Instantly share code, notes, and snippets.

@mehulkar
Last active August 29, 2015 14:07
Show Gist options
  • Save mehulkar/dca4b66e9e2e25f6f591 to your computer and use it in GitHub Desktop.
Save mehulkar/dca4b66e9e2e25f6f591 to your computer and use it in GitHub Desktop.
ActiveModelSerializers

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": []
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment