2011-12-17 107 views
1

我在嵌套模型示例中使用codebrew \ backbone-rails(比如说我有一个任务集合,每个集合都可以有一个Details集合 - 类似于例如。)Backbone.js - 关于使用rails和嵌套集合的指导

我可以加载并创建一系列嵌套的视图来显示我想要的数据,但是现在当我试图对该数据执行CRUD操作时,我卡住了。

例如 - 说我更改我的外部(上?)对象上的属性,并且想要将该数据发送到服务器。这是json的样子。自从我“急切地”装我的嵌套的数据,当我加载应用程序,我将它发送回服务器上的更新(看details_attributes格式)

{ 
    "task" => { 
         "name" => "testupdate", 
        "user_id" => 1, 
         "id" => 3, 
        "Details" => [ 
      [0] { 
         "task_id" => 3, 
        "break_length" => 4, 
         "completed" => false, 
          "id" => 12, 
         "length" => 25, 
        "location_id" => nil, 
          "note" => "test444", 
       "start_date_time" => "2011-12-15T00:00:00Z" 
      } 
     ], 
     "details_attributes" => [ 
      [0] { 
       "start_date_time" => "2011-12-15T00:00:00Z", 
         "completed" => false, 
          "note" => "test444", 
        "break_length" => 4, 
         "task_id" => 3, 
          "id" => 12, 
         "length" => 25, 
        "location_id" => nil 
      } 
     ] 
    } 
} 

仅供参考 - 我另一方面,如果我在服务器上执行了这种更改,使用老式的rails方式(使用嵌套的形式),我发送一个包含“_attributes”的集合嵌套对象的散列(尽管在本例中只有一个(看Details_attributes):

{ 
        "utf8" => "", 
    "authenticity_token" => "iv9wYvgqLt3nldVOX4AeAifpFaSHIfEj85MsPUaMiAw=", 
        "task" => { 
         "name" => "test", 
     "details_attributes" => { 
      "0" => { 
         "_destroy" => "", 
       "start_date_time" => "2011-12-15 00:00:00", 
         "length" => "25", 
         "completed" => "0", 
          "note" => "test444", 
        "break_length" => "4", 
          "id" => "12" 
      } 
     } 
    }, 
       "commit" => "Update task", 
       "user_id" => "1", 
        "id" => "3" 
} 

如何让我的JSON,在更新任何指导,看起来像它应该服务器接受呢?

感谢您的任何帮助。

回答

1

您可以提供自定义同步方法来覆盖默认序列化。比如(我希望我不是太远离你的设置)

var json='{"name":"testupdate", "user_id":1, "id":3, "details_attributes":[{"start_date_time":"2011-12-15T00:00:00Z", "completed":false, "note":"test444", "break_length":4, "task_id":3, "id":12, "length":25}]}'; 

Task = Backbone.Model.extend({ 
    initialize:function() { 
     this.attrs=new DetailsAttributes(this.get("details_attributes")); 
    }, 
    sync: function(method, model, options) { 
     if (method == 'update') { 
      var data = this.toJSON(); 
      data.details_attributes = {}; 
      this.attrs.each(function(model, ix) { 
       data.details_attributes[ix] = model.toJSON(); 
      }); 

      console.log(JSON.stringify(data)); 

      options = _.extend({data: data}, options); 
     } 


     return Backbone.sync.call(this, method, this, options); 
    } 
}); 
DetailAttribute= Backbone.Model.extend(); 
DetailsAttributes= Backbone.Collection.extend({ 
    model:DetailAttribute 
}); 
var tk= new Task(JSON.parse(json)); 
tk.save(); 

http://jsfiddle.net/5gZr5/4/,如果你想检查控制台日志。

Backbone.sync将使用序列化选项中传递的数据属性。

+0

这是接近我 - (和我不是一个JavaScript专家) - 我可以看到什么看起来在我的控制台日志更好,但是当我把它发送到服务器,我的JSON看起来是这样的:`{“对象对象 “=>零, ”USER_ID“=>” 1" , “ID”=> “6”}` - 我做错事时,我呼吁Backbone.sync超... – 2011-12-17 15:37:53