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

前端 未结 6 1970
灰色年华
灰色年华 2021-02-01 18:38

In a standard Rails controller, I\'d create a record like this:

@user = User.new(params[:user])

This assumes that the form parameters that come

6条回答
  •  花落未央
    2021-02-01 19:11

    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.js
    User = 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.

提交回复
热议问题