tiagopog/jsonapi-utils

Possible to render a record that hasn't been persisted?

adambedford opened this issue · 1 comments

One of my endpoints needs to just build a record and return the attributes, rather than persisting it. When using jsonapi_render with the unsaved model, all I get on the frontend is { "data": null }.

Is there a way to do this or is it by design?

Sure, the thing is: in order to keep compliant with JSON API's specs you still need to generate the identifier for that resource otherwise a body like { "data": null } will be rendered.

Quick example:

class UsersController < ApplicationController
  def fake_user
    user = User.new(id: SecureRandom.uuid, first_name: 'Foobar')
    jsonapi_render json: user
  end
end

Then when this endpoint is called we got the following response:

GET /fake_user

{
    "data": {
        "id": "0d1567cc-c0db-4894-b172-b8729c171ba2",
        "type": "users",
        "links": {
            "self": "http://api.mydomain.com/users/0d1567cc-c0db-4894-b172-b8729c171ba2"
        },
        "attributes": {
            "first_name": "Foobar",
            "last_name": null,
            "full_name": "Foobar "
        },
        "relationships": {
            "posts": {
                "links": {
                    "self": "http://api.mydomain.com/users/0d1567cc-c0db-4894-b172-b8729c171ba2/relationships/posts",
                    "related": "http://api.mydomain.com/users/0d1567cc-c0db-4894-b172-b8729c171ba2/posts"
                }
            }
        }
    }
}