PATCH request sends all the attributes

It is normal behaviour that when updating just a single attribute of a model, Ember sends all the model attributes in a PATCH request instead of single one that was modified (compared to other frameworks, like Rails for example)?

1 Like

I think it’s pretty common. In general, there aren’t super clear standards for restful JSON apis, other than JSON:API. If you’re using JSON:API, it says that PATCH is free to include only fields that you want to change. And I agree that can convey intent better. If some unrelated fields have changed concurrently, a more sparse PATCH can avoid an unnecessary conflict.

On the other hand, it can be surprising if the user intends to save a particular state, and ends up with a different state caused by combining their changes with another user’s concurrent changes in a way that ends up with two fields in the model not making logical sense together. So it can also be better to always send all the fields.

So it’s a domain-specific issue that can vary.

I don’t know of an easy way to make ember-data send only changed fields. Maybe somebody else can chime in on that.

Thank you @ef4, for this detailed explanation. I’m on the way to implement a role-based authorization using ember-can on Ember side and Pundit on the Rails side (backend API) with JSON API. The problem I hit is to enable a field-level authorization when updating a model. This is how I discovered that Ember sent all the attributes. I make the unauthorized fields disabled on Ember side but this has no impact on the posted attributes (all of them are posted with PATCH). So even if Pundit gem makes it possible to control/filter strong parameters (posted attributes), it fails if used with Ember. :confused:. So, I’m kinda lost how to implement this feature…

I don’t know anything about Pundit, but the last time I implemented role-based auth on a JSON:API server I handled this server-side by comparing the existing record with the requested PATCH. Any fields that aren’t changing don’t require write permissions.

You can use the snapshot.changedAttributes() API to quickly get a list of what you want to include in your patch.

@runspired Ah, cool, thank you! When applied, the next step would be to remove the undesired attributes before posting them, right? As the API docs say:

Returns all changed attributes and their old and new values

Is there a way to see new and old values (I mean how to distinguish them)?

The return value is an object whose keys are the attributes that have changed and whose values are an array with two items, the old value and the new value (in that order).

1 Like

Cool, thank you very much. I think, finally, there is no need to filter the attributes on Ember side. The initial idea was to raise an exception on the backend side in case of unpermitted attributes (that’s how it is supposed to work). But I think to opt to just filter them out (default behaviour in Rails).