Search code examples
ruby-on-railsbackbone.js

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


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() {
    if(this.get('engine') != undefined) this.engine = new Engine(this.get('engine'));
  }
}

var redCar = new Car({
      'color': 'red',
      // The controller nests the model
      'engine': {
         'horsepower': '350'
       }
    });


redCar.save()

What is the right way to send engine_attributes to the controller? (Car accepts_nested_attributes_for :engine, so it expects engine_attributes.) Do I override the Backbone sync()? Is there a better convention to follow for nested models?

Maybe I should not be returning nested models from the controller, or returning engine_attributes instead of engine?

On a side note, I am using the Rails respond_with(@car, :include => :engine) (same as @car.to_json(:include => :engine). The fact that this api nests the engine attributes under engine but the model expects engine_attributes seems contradictory - I've never been sure how to reconcile this.


Solution

  • 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.