0

我有一個模型約會有很多任務。主幹更新嵌套集合與ID。 (Rails後端)

創建一個新的任務模型,其中任務與骨幹工作正常。但是,當我嘗試更新不同任務的ID的模型它不工作。

我收到以下錯誤:

ActiveRecord::AssociationTypeMismatch: Task(#1192000) expected, 
got ActiveSupport::HashWithIndifferentAccess(#2458300) 

參數:

{"appointment"=> 
    {"id"=>"36", 
    "customer_id"=>"19", 
    "employee_id"=>"10", 
    "done"=>"", 
    "notes"=>"", 
    "starts_at"=>"2012-09-05 13:00:00 +0200", 
    "ends_at"=>"2012-09-05 14:30:00 +0200", 
    "bookingtype"=>"", 
    "tasks"=> 
     "[{\"created_at\"=>\"2012-09-04T13:37:17+02:00\", 
      \"duration\"=>\"60\", \"id\"=>\"12\", 
      \"task_category_id\"=>\"5\", \"updated_at\"=>\"2012-09-04T13:46:13+02:00\"}]", 
    "appointment"=>"", 
    "task_ids"=>"[\"12\"]"}, 
    "action"=>"update", 
    "controller"=>"appointments", 
     "id"=>"36"} 

我有一些想法,問題是,有在請求任務和task_ids,但我不知道如何解決這個問題。

我更新的方法是這樣的:

save: function() { 
      var self = this;   

      var tasks = []; 

      $("input:checked").each(function() {     
       tasks.push($(this).val()); 
      }); 

      this.model.save({starts_at: this.$('#appointment_starts_at_modal').val(), employee_id: this.$('#employeeSelect').val(), customer_id: this.$('#customerSelect').val(), 
         "starts_at(5i)": this.$('#appointment_starts_at_5i_modal').val() , 
         "ends_at(5i)": this.$('#appointment_ends_at_5i_modal').val(), task_ids: tasks}, { 
      success: function(model, resp) { 
       self.model = model; 

       self.close(); 
      }, 
      error: function() { 
       //new App.Views.Error(); 
      } 
     }); 
     return false; 
    }, 

回答

1

從錯誤中,這聽起來像一個Ruby的問題,我不熟悉的紅寶石在所有。但是,就Backbone而言,在約會模型中有一個「tasks」和「task_ids」屬性應該不成問題。骨幹會高興地將這些作爲JSON數據發送到您的服務器。但是請注意,在Backbone中處理嵌套集合時,您將id作爲任務模型外的屬性傳遞的方式有點奇怪。 :-)

雖然我可以談論一些關於我從骨幹視角看到的東西。

我假設你的tasks_ids屬性代表你擁有的所有任務的ID數組。 tasks是任務JSON對象的數組()。在Backbone中,在處理嵌套集合等時,通常每個任務的id屬性將成爲任務對象的一部分。所以,如果我做了送了一堆任務的數據作爲陣列的應用程序,它會發出這樣看:

"tasks"=> 
    "[{\"id"=>\"12\", \"created_at\"=>\"2012-09-04T13:37:17+02:00\", 
     \"duration\"=>\"60\", \"id\"=>\"12\", 
     \"task_category_id\"=>\"5\", \"updated_at\"=>\"2012-09-04T13:46:13+02:00\"}]", 

當我與嵌套集合工作,我基本上確保id和一些模型的所有屬性被對象封裝。

// My fake JSON 
{'id':'1', 'appointment':{ 
    'id':'50', 
    'tasks':[ 
     {'id':'100', 'taskName':'groceries' /* etc. */}, 
     {'id':'200', 'taskName':'bank errand'} 
    ] 
}} 

當我被任命模型接收該獲取的數據,我會任一方法在我parse()或修改set()方法。我就證明我做什麼用parse()

// Inside my appointment model definition 
parse: function(response) { 
    if (_.isUndefined(this.tasks)) { 
     this.tasks = new TasksCollection(); 
    } 
    this.tasks.reset(response.tasks); 
    delete response.tasks; 

    return response; 
} 

喜歡的東西上面。我TasksCollection會model: Task定義,以便與屬性的哈希將填充嵌套我有合適的數據模型的任命在我的收藏復位(使用IDS包括在內。)

我不認爲這能解決你的問題,但因爲你是暗指到骨幹的做事方式,我認爲有這種方式(很多)說明可能會給你一些想法。