gpt4 book ai didi

ruby-on-rails - 使用 Rails、backbone.js 和 accepts_nested_attributes_for 保存嵌套对象

转载 作者:行者123 更新时间:2023-12-03 11:17:42 25 4
gpt4 key购买 nike

我正在使用 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到 Controller ? (汽车 accepts_nested_attributes_for :engine ,所以它期望 engine_attributes 。)我是否覆盖主干 sync() ?嵌套模型是否有更好的约定?

也许我不应该从 Controller 返回嵌套模型,或者返回 engine_attributes而不是 engine ?

附带说明一下,我正在使用 Rails respond_with(@car, :include => :engine) (与 @car.to_json(:include => :engine) 相同。这个 api 将引擎属性嵌套在 engine 下,但模型期望 engine_attributes 的事实似乎是矛盾的 - 我一直不确定如何协调这一点。

最佳答案

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

toJSON: function(){

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

}

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

关于ruby-on-rails - 使用 Rails、backbone.js 和 accepts_nested_attributes_for 保存嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5226067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com