Saving nested objects with Rails, backbone.js, and accepts_nested_attributes_for

后端 未结 4 1384
心在旅途
心在旅途 2020-12-07 23:30

I\'m using Rails, backbone.js (learning this now). Let\'s say you have two models, Car and Engine.

var Car = Backbone.Model.extend({
  initialize: function(         


        
相关标签:
4条回答
  • 2020-12-07 23:42

    Very helpful. I was working with a similar situation, and this example did not work for me at first. In my example I have a has_many / belongs_to relation. For example a car has_many :tires.

    The problem I encountered was that the tires_attributes needed to be nested INSIDE of the car json, not adjacent to it. I ended up with something like this:

    toJSON: function(){
    
      json = {car : this.attributes};
      json.car.tires_attributes = this.get('tires').toJSON();
      return json;
    
    }
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-07 23:42

    I found this gem! Maybe help you.

    http://blog.dtmtec.com.br/blog/2013/05/power-up-your-backbone-models-with-nested-attributes/

    0 讨论(0)
  • 2020-12-07 23:45

    I would suggest to override toJSON on the backbone model.

    toJSON: function(){
    
      json = {car : this.attributes};
      return _.extend(json, {engine_attributes: this.get("engine").toJSON());
    
    }
    

    toJSON is called within the sync method just before sending data to the backend.

    0 讨论(0)
  • 2020-12-07 23:57

    I believe we've to do something with (or around) Backbone sync or with rails backend, because the problem in communication between two. Overriding toJSON() method might lead to unexpected results, because this is general purpose method and others parts of application might rely on, for example views.

    Possibly quick solution:

    redCar.save({}, {
        contentType: 'application/json',
        data: JSON.stringify({car: redCar.toJSON(), engines_attributes: redCar.get('engines').toJSON()})
    });
    
    0 讨论(0)
提交回复
热议问题