使用 Rails、backbone.js 和 accepts_nested_attributes_for 保存嵌套对象 [英] Saving nested objects with Rails, backbone.js, and accepts_nested_attributes_for

查看:19
本文介绍了使用 Rails、backbone.js 和 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,所以它需要 engine_attributes.)我是否覆盖 Backbone sync()?对于嵌套模型,是否有更好的约定可遵循?

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 而不是 engine?

Maybe I should not be returning nested models from the controller, or returning engine_attributes instead of engine?

顺便说一句,我正在使用 Rails respond_with(@car, :include => :engine)(与 @car.to_json(:include => 相同:引擎).事实上,这个 api 将引擎属性嵌套在 engine 下,但模型期望 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆