Backbone.js and Rails - How to handle params from Backbone models? Backbone.js and Rails - How to handle params from Backbone models? ruby-on-rails ruby-on-rails

Backbone.js and Rails - How to handle params from Backbone models?


It's nice when you can have the general Rails forms and Backbone forms match with respect to the root node. That's why in my last application I chose to override the Backbone models' toJSON method.

You could override the global toJSON method as Raimonds Simanovskis suggested. But even the non-DRY way approach isn't so bad. Just one line of boilerplate for each model definition:

// Depends on Underscore.jsUser = Backbone.Model.extend({  toJSON: function() {    return { user: _.clone( this.attributes ) }  },  // Your other methods here});

Edit: Corrected code sample. Sorry for the errors, I was translating from CoffeeScript to JavaScript.


If you are using the backbone-rails gem, looks like you can do

var User = Backbone.Model.extend({   paramRoot: 'user'});

Around line 45 on github

Credit PL J and stream 7 on this link


I have made a little hack to namespace save requests under model.name property.It monkey patches toJSON() during sync() call only and restores original method so you can use it as usual.

I have implemented it in CoffeeScript.

Check it here