tiagopog/jsonapi-utils

Updating a relationship?

derekcannon opened this issue · 2 comments

When I add jsonapi_resources :foo to routes.rb, given I have a FooResource and a BarResource where FooResource has_one Bar, I get additional routes like api/v2/foo/:foo_id/relationships/bar. I notice that the route created references a method called update_relationship.

However, I could not find any examples of what an update would look like using this methodology. According to JSON API, updating a resource looks like this:

PATCH /articles/1/relationships/author HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": { "type": "people", "id": "12" }
}

(http://jsonapi.org/format/#crud-updating-to-one-relationships)

How is update_relationship supposed to work with data coming in in this format? Is there some sort of jsonapi-utils helper for doing something like foo.update(bar) in this case?

Hey there, @derekcannon!

As you've noticed jsonapi_resource draws routes based on what is specified by json:api, dealing only with resource identifier objects (i.e. "data" contains only "type" and "id"). JSONAPI::Resources provides then the action method that matches to the given route out of the box, so you actually don't need to write anything else in order to see it working.

Alternatively, with JSONAPI::Utils you could also redefine the update_relationship method in the FoosController and write the update operation in the Rails-way (or using service objects, interactors etc), using JU's helpers such as jsonapi_render to build the response properly.

Thanks