Ale*_*eth 23 ruby-on-rails backbone.js
我正在使用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()
Run Code Online (Sandbox Code Playgroud)
发送engine_attributes给控制器的正确方法是什么?(汽车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似乎是矛盾的 - 我从来没有确定如何调和它.
Jul*_*ien 33
我建议在骨干模型上覆盖toJSON.
toJSON: function(){
json = {car : this.attributes};
return _.extend(json, {engine_attributes: this.get("engine").toJSON());
}
Run Code Online (Sandbox Code Playgroud)
在将数据发送到后端之前,在sync方法中调用toJSON.
| 归档时间: |
|
| 查看次数: |
7365 次 |
| 最近记录: |