ruby-on-railsrestjson-apijsonapi-resources

JSON API delete 'has and belongs to many' relationship


I'm building an API for a cart-like thing with the jsonapi-resources gem, and I need an endpoint to remove an item from the cart.

Currently, I'm assuming that a client consuming this API won't need the actual 'cart items'. Instead it just needs a list of the products that are in the cart.

However, there doesn't seem to be any way to delete something in jsonapi-resources without knowing that thing's ID. I.e. there's no way for a client to remove something from the cart without it knowing the id of the join model.

Basically I need an endpoint that does something like:

DELETE http://example.com/carts/1/cart-items?filter[product]=1

Instead, the only option I can find is

DELETE http://example.com/cart-items/1

Alternatively, I could implement a custom action to handle this, but I've gone through the docs and I can't find a prescribed way of writing custom actions.


Solution

  • After struggling with this for hours, in the process of writing this question I finally worked out the answer. It's not at all well documented, though — I had to read through the gem's tests to work it out.

    curl -X DELETE -H "Content-Type: application/vnd.api+json" \ --data '{ "data" : [{"type": "products", "id": 185 }] }' \ http://localhost:3000/api/v1/carts/4085/relationships/products

    This successfully deleted the item from the cart (and did not touch the product record itself).