Picture of Mehul Kar

Mehul Kar

Link to Twitter profile Image of envelope to indicate email link

Oct 02, 2014

Active Model Serializers has_many association

programming rails

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

Want to talk about this blag? Email me or send me a toot @mehulkar!