Skip to content

Instantly share code, notes, and snippets.

@justinperkins
Created October 18, 2012 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinperkins/3909887 to your computer and use it in GitHub Desktop.
Save justinperkins/3909887 to your computer and use it in GitHub Desktop.
Backbone.js + Rails: Add Auth Token to Sync
// Adapted from: https://gist.github.com/1251730
// I like this technique better: https://gist.github.com/3960219
$(function(){
var paramName = $("meta[name='csrf-param']").attr('content');
var paramValue = $("meta[name='csrf-token']").attr('content');
Backbone.sync = _.wrap(Backbone.sync, function(originalSync, method, model, success, error){
if (method == 'create' || method == 'update' || method == 'delete') {
// grab the token from the meta tag rails embeds
var auth_options = {};
auth_options[paramName] = paramValue;
// set it as a model attribute without triggering events
model.set(auth_options, {silent: true});
}
// proxy the call to the old sync method
return originalSync(method, model, success, error);
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment