2012-05-24 151 views
-2

好的,所以我們推出了第一個Backbone JS應用程序,現在我們有了新的問題。 顯然,當我最初爲評論和評論加載模型時,它們具有包含添加時間戳的「created_at」屬性。當我編輯評論然後做model.sync()時,它會將「created_at」傳遞迴服務器。現在,RoR應用程序會跳出來討論它,而且正如我們的Rails開發人員告訴我的那樣,我不能在任何情況下將「created_at」傳回服務器,並且它僅計算用於顯示。Backbone JS和Ruby on Rails的新問題

現在有東西必須給。要麼我必須破解Backbone,並在sync()之前刪除一些屬性,或者在Rails方面做一些事情。

你對這個解決方案的建議是什麼?

而且無論如何,在model.sync()過程中不能傳遞某些屬性可以做些什麼?我將衷心感謝您的幫助。

+3

應該有路過'created_at'回服務器沒問題,只要你的Rails應用程序是妥善書寫和保護。你的Rails開發是錯誤的。 – meagar

回答

1

您可以添加到您的模型:

attr_protected :created_at, :updated_at 
+0

謝謝。與Rails開發者有過爭論。這個。他說這阻止了他從命令行手動覆蓋created_at,所以他不會使用它。好的。我最終在同步之前刪除「created_at」。無論如何,它都會通過回覆。所以它工作。 –

+0

當您使用attr_protected進行created_at保護時,它不允許像user.update_attributes(params [:user])中那樣進行批量賦值;不過,你仍然可以做user.created_at = some_value – Roman

1

我遇到了這個確切的問題,試圖張貼到不可變的屬性。 Backbone模型的問題是,默認情況下,它們發佈全部或全部。但你可以做部分更新。爲了解決這個問題,我創建了一個Backbone.Model後裔,推翻像這樣的model.save:

save : function(key, value, options) { 
     var attributes, opts; 

     //Need to use the same conditional that Backbone is using 
     //in its default save so that attributes and options 
     //are properly passed on to the prototype 
     if (_.isObject(key) || key == null) { 
      attributes = key; 
      opts = value; 
     } else { 
      attributes = {}; 
      attributes[key] = value; 
      opts = options; 
     } 

     //Now check to see if a partial update was requested 
     //If so, then copy the passed attributes into options.data. 
     //This will be passed through to Backbone.sync. When sync 
     //sees that there's an options.data member, it'll use it instead of 
     //the standard attributes hash. 
     if (opts && opts.partialUpdate) { 
      opts["data"] = JSON.stringify(attributes); 
      opts["contentType"] = "application/json"; 
     } 

     //Finally, make a call to the default save now that we've 
     //got all the details worked out. 
     return Backbone.Model.prototype.save.call(this, attributes, opts); 
    } 

這讓我我想要的屬性,選擇性地發佈到後臺,像這樣:

//from the view - the GET may have delivered 20 fields to me, but I'm only interested 
//in posting the two fields. 
this.model.save({ 
    field1 : field1Value, 
    field2 : field2Value 
},{ 
     partialUpdate : true 
}); 

不能告訴你這是怎麼讓我的生活變得如此簡單!現在,有人可能會問,爲什麼不通過changedAttributes()JSON?原因是因爲在某些情況下,已更改的屬性僅適用於客戶端,特別是要引用對也使用該模型的視圖的更改。

在任何情況下,嘗試了這一點...

+0

謝謝。但它對骨幹源來說看起來太過分了。我最終在同步之前刪除了「created_at」 - 在任何情況下,它都通過響應傳遞,一旦同步,它就包含原始的created_at屬性。 –

+0

但實際上並沒有與Backbone源代碼混淆。這是一個簡單的保存覆蓋。噢... –