Skip to content

Instantly share code, notes, and snippets.

@Peleg
Created August 7, 2014 21:03
Show Gist options
  • Save Peleg/464597e9d74f65f2a836 to your computer and use it in GitHub Desktop.
Save Peleg/464597e9d74f65f2a836 to your computer and use it in GitHub Desktop.
Overwriting backbone params to comply with rails conventions
// Overwrite Backbone#sync in order to allow easy form submissions
(function ($) {
// Modify params in order to follow the Rails convention:
// comments: [Obj, Obj] => comments_attributes: { 0: Obj, 1: Obj }
// video: { id: 2, title: 'foo' } => video_attributes: { id: 2, title: 'foo' }
var railifyParams = function (params) {
for (var key in params) {
if (!params.hasOwnProperty(key)) continue;
if (params[key] instanceof Object) {
params[key + '_attributes'] = (params[key] instanceof Array) ? toObj(params[key]) : railifyParams(params[key]);
delete params[key];
}
}
return params;
};
// Recursively turn Array to Object converting indices to Obj keys
var toObj = function (arr) {
var obj = {};
for (var i = 0; i < arr.length; i ++) {
if (arr[i] instanceof Array) arr[i] = toObj(arr[i]);
obj[i] = arr[i];
}
return obj;
};
var _OldBackboneSync = Backbone.sync;
Backbone.sync = function (method, model, options) {
if (options.data == null && model && ['create', 'update', 'patch'].indexOf(method) !== -1 ) {
options.contentType = 'application/json';
data = JSON.stringify(options.attrs || model.toJSON(options));
if (model.paramRoot) {
data = {};
data[model.paramRoot] = railifyParams(model.toJSON(options));
} else {
data = model.toJSON();
}
options.data = JSON.stringify(data);
}
return _OldBackboneSync.apply(Backbone, arguments);
};
})(jQuery);
@pathouse
Copy link

pathouse commented Aug 7, 2014

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment