Search code examples
active-model-serializersjson-api

Active Model Serializer remove relationship member when using JSON API


I'm using the latest AMS v0.10.0.rc3 with the JSON API adapter.

So far is working great and is adding some useful conventions that i would like to change.

For example, lets suppose that i have a Post serializer and a Comment serializer like this:

class Post < ActiveModel::Serializer
  attributes :id, :title
  has_many :comments
end

class Comment < ActiveModel::Serializer
  attributes :id, :comment
  belongs_to :post
end

Then if i request /posts/1 for example i get the following

{
  "data": {
    "id": "1",
    "type": "posts",
    "attributes": {
      "title": "My awesome title",
    },
    "relationships": {
      "comments": {
        "data": [
          {
            "id": "1",
            "type": "comments"
          },
          {
            "id": "2",
            "type": "comments"
          }
        ]
      }
    }
  }
}

Notice how the relationships member appears and according with the spec is marked as an optional member with MAY. It is a nice convention that i need to override some times.

So my question is:

  • How i remove the relationship member at the serializer or controller level ?

(If i miss some detail please comment and i will update the question.)


Solution

  • Currently, your best option is to define two serializers, one with the associations, one without, and specify in your render call which to use (render json: posts, each_serializer: PostWithoutAssociationsSerializer).

    There is an ongoing discussion about adding an include_if option to associations and attributes, which you could potentially leverage if it gets merged.