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

前端 未结 6 1964
灰色年华
灰色年华 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 18:51

    As of Rails 3.1 there's now a new initializer called wrap_parameters.rb which handles this problem by default. The code that handle this case is:

    # Disable root element in JSON by default.
    ActiveSupport.on_load(:active_record) do
      self.include_root_in_json = false
    end
    

    Bada bing!

    0 讨论(0)
  • 2021-02-01 18:53

    It should be noted that if you opt for the currently accepted answer (patching toJSON at the model level) you are affecting reading as well. Maybe that goes without saying, maybe not. But you will have a lot of work to do when rendering models/collections if you put this patch into affect in a backbone app. Therefore, I personally wouldn't use it as-is.

    0 讨论(0)
  • 2021-02-01 19:02

    In one of the answers to Rails mass assignment and Backbone.js there is mentioned patch https://gist.github.com/719080 which I think will do what you need.

    0 讨论(0)
  • 2021-02-01 19:04

    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

    0 讨论(0)
  • 2021-02-01 19:06

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题