节约使用Rails嵌套的对象,Backbone.js的,和accepts_nested_attributes_for [英] Saving nested objects with Rails, backbone.js, and accepts_nested_attributes_for
问题描述
我使用Rails,Backbone.js的(现在正在学习这一点)。比方说,你有两个型号,轿车和发动机。
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()
什么是发送 engine_attributes
到控制器的正确方法? (汽车 accepts_nested_attributes_for:发动机
,所以预计 engine_attributes
。)我重写主干同步()
?有没有更好的惯例遵循嵌套模式?
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?
也许我不应该从控制器返回嵌套模式,或返回 engine_attributes
而不是引擎
?
Maybe I should not be returning nested models from the controller, or returning engine_attributes
instead of engine
?
在一个侧面说明,我使用Rails respond_with(@car,:包括=>:发动机)
(等同于 @car .to_json(:包括=>:引擎)。
这个API巢之下发动机发动机属性
但该模型预计,这一事实 engine_attributes
似乎矛盾 - 我从来没有知道如何调和这种
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.
推荐答案
我会建议覆盖的toJSON的骨干机型。
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是同步方法中只是将数据发送到后端之前调用。
toJSON is called within the sync method just before sending data to the backend.
这篇关于节约使用Rails嵌套的对象,Backbone.js的,和accepts_nested_attributes_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!