使用Rails,backbone.js和accepts_nested_attributes_for保存嵌套对象

我正在使用Rails,backbone.js(现在就学习这个)。 假设您有两种型号,Car和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() 

engine_attributes发送到控制器的正确方法是什么? (Car accepts_nested_attributes_for :engine ,所以它期望engine_attributes 。)我是否覆盖Backbone sync() ? 嵌套模型是否有更好的约定?

也许我不应该从控制器返回嵌套模型,或返回engine_attributes而不是engine

另外,我正在使用Rails respond_with(@car, :include => :engine) (与@car.to_json(:include => :engine) 。事实上,这会将引擎属性置于engine下但是模型期望engine_attributes似乎是矛盾的 – 我从来没有确定如何调和它。

我建议在骨干模型上覆盖toJSON。

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

在将数据发送到后端之前,在sync方法中调用toJSON。

很有帮助。 我正在处理类似的情况,这个例子起初对我不起作用。 在我的例子中,我有一个has_many / belongs_to关系。 例如汽车has_many:轮胎。

我遇到的问题是,tire_attributes需要嵌套在汽车json的INSIDE中,而不是与它相邻。 我最终得到了这样的东西:

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

希望这可以帮助。

我相信我们要用(或围绕)Backbone sync或者使用rails后端做一些事情,因为两者之间的通信问题。 覆盖toJSON()方法可能会导致意外结果,因为这是通用方法,而应用程序的其他部分可能依赖于,例如视图。

可能快速的解决方案:

 redCar.save({}, { contentType: 'application/json', data: JSON.stringify({car: redCar.toJSON(), engines_attributes: redCar.get('engines').toJSON()}) });