Skip to content

JsonApi empty, to-one relationship? #1938

Open
@lygaret

Description

@lygaret

Firstly; this project is amazing, thank you all.

I'm trying to build out a JSON API service, and am running into an issue when rendering fetched relationships.

According to the spec: http://jsonapi.org/format/#fetching-relationships-responses

If the above relationship is empty, then a GET request to the same URL would return:

HTTP/1.1 200 OK
Content-Type: application/vnd.api+json

   {
     "links": {
       "self": "/articles/1/relationships/author",
       "related": "/articles/1/author"
     },
     "data": null
   }

But, from what I can tell, you're not allowed to pass nil into the serializer, as I'm running into undefined method \read_attribute_for_serialization' for nil:NilClass` with the following code:

  def relationship_owner
    owner = @item.owner(scope.current_organization)
    respond_to do |format|
      links = {
        related: owner_v2_item_url(id: @item.id),
        self:    relationship_owner_v2_item_url(id: @item.id)
      }

      format.jsonapi {
        render jsonapi: item, fields: { user: [] }, links: links
      }
    end
  end

Now, I'm not sure if this is expected to work; I've seen some references in other tickets that the data item is required. That being said, I'm not sure how I'd build this out, other than resorting to manually creating the JSON, and I'd like to not do this for every relationship that's nullable.

Any idea how I should be proceeding?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions