Skip to main content
 首页 » 编程设计

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

2025年01月19日14luoye11

我正在使用 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。