If you want to prevent redundant inclusion of associations, set embed
:
embed :objects # Embed associations as full objects
embed :ids # Embed only the association ids
embed :ids, :include => true # Embed the association ids and include objects in the root
So
class Comments < ActiveModel::Serializer
embed :ids, include: true
end
will include the post only once at the top level:
{
comments: [
{
id: 1,
text: "Foo",
post_id: 1
},
{
id: 2,
text: "Bar",
post_id: 1
}
],
posts: [
{
id: 1,
title: "Lorem ipsum"
}
]
}
If you want to include or leave out associations completely depending on the situation, this wonderful StackOverflow answer has a nifty solution for that by (ab)using eager loading:
class Comments < ActiveModel::Serializer
attributes :id, :text, :poster_id
belongs_to :poster
def include_poster?
object.association(:poster).loaded?
end
def include_poster_id?
!include_poster?
end
end
Now by clearing the post
association you can prevent it from being included at all:
@comments = @post.comments
@comments.post.reset
respond_with @comments
In reverse, explicitly eager loading an association will include it:
@comments = Comment.includes(:poster).order(id: :asc).limit(10)
respond_with @comments