Reputation: 21556
I know this has been asked before, and I have it working, but I'm not sure how/why it works and was hoping somebody could explain it to me.
I have a model and I'm changing only one attribute at a time. I don't want to send the entire model to the server each time, as there is no need with edit in place editing.
I save the model like this
update_field: function(e){ var value = $('#update').val(); var key = $(e.currentTarget).parent().attr('id'); MyModel.attributes[key] = value; MyModel.save({key: value},{patch: true},{ success: function(){ alert('saved'); }, error: function(){ alert('problem updating recipe'); }}); },
when I view the payload of what is sent to the server, the entire model is being sent, but the rails console only shows the updated field being updated. I find this impressive, but confusing at the same time. How does it know what needed to be updated.
I think my largest complaint with this is that Paperclip attempts to save an attachement, even though no attachement is being saved in the update.
Is there something I'm doing wrong here? How does Backbone tell Rails which attributes to update. Is there a way to truly only send the necessary attributes?
Also, for some reason my success function isn't being triggered. Though I doubt that is related.
Upvotes: 1
Views: 352
Reputation: 35960
The patch synchronization doesn't send the whole model, it only sends the attributes you provide to model.save()
as the first argument:
model.save({foo: 'bar'}, {patch:true}); // -> PATCH /model/id {foo:bar}
I'm going to go on a limb here and guess that you're using an older version of Backbone. PATCH
support was only added in 0.9.9
, and in the earlier versions the patch:true
argument would simply ignored. If this is correct, then you're actually sending a PUT
request to the resource.
I don't know enough Rails to say what it means when you say that the console shows only the updated fields being updated, but since you're sending an update after every field change, then ActiveRecord / whatever ORM you might be using is probably intelligent enough to only copy and update the fields that have actually changed -- in your case, the field that you expected, because all the other fields match the fields already in your database.
Or then I could be completely off-base, and there is actually something else wrong. Please reply if this is the case, and I'll edit / delete my answer.
Edit: Also, your success handler is not being called, because you pass it incorrectly. Instead of passing three arguments as you do here:
MyModel.save({key: value},{patch: true},{success:...});
The save method only expects two arguments, the attributes to set, and the options hash, which may define multiple options, including patch
and success
:
MyModel.save({key: value},{patch: true, success:...});
Upvotes: 1