0

在我的一个主干视图中,我一直在努力处理一种形式。该表格用于保存项目模型的信息(例如项目名称、项目描述、项目成员)。虽然项目特定信息没有任何问题地保存到相应的数据库表中,但我没有设法将项目-用户关系保存在联合数据库表中(projects_users,包含两个实体的相应 ID)。可以在表单中添加到项目中的用户已经存在于数据库中,因此无需将任何内容添加到用户数据库表中。

谁能在这里让我走上正确的轨道?我尝试了解 Backbone 中的关系。这些是我已经研究过的两个链接,但无法将其内容转化为解决方案:

骨干关系

Rails 和 Backbone 中的模型关系

谢谢你,亚历山德拉

编辑

有人建议我这边的一些代码会很有用。由于我对自己需要做什么没有很好的理解,所以我的代码现在几乎是一团糟……但让我试试。

我的表单视图:

App.Views.Projects.Common.Form = Backbone.View.extend({
...

  submitted: function(formElement) {
      var newData = this.serializeFormData(formElement);

      this.model = new App.Models.Project({
        name        : newData.name,
        description : newData.description
        // Somehow put the users array associated with the project here ...
      });

      this.saveFormData(newData);
      return false;
  },


  serializeFormData: function(formElement) {
    var fields = formElement.serializeArray();

    var serializedData = {};
    $.each(fields, function(index, field) {
      serializedData[field.name] = field.value;
    });

    return serializedData;
  },


  saveFormData: function(newData) {
    var project = this.model;

    // placeholder for the users that would be associated with the project
    // parsing of the data from the form is required to get a corresponding array of user models
    var users = App.users;
    project.attributes.users = users;

    // this line should save the project to the database table and the project-users relationships
    // in the projects_users table; it needs the success and error functions
    project.save({}, {});    
  },

...
})

对于项目和用户模型文件,我是按照以下思路考虑的:

App.Models.Project = Backbone.RelationalModel.extend({    
  urlRoot: '/projects',

  // Default attributes for the project.
  defaults: {
    description: "",
    users: []
  },

  relations: [{
    type         : Backbone.HasMany,
    key          : 'users',
    relatedModel : 'App.Models.User'
  }]
});


App.Models.User = Backbone.RelationalModel.extend({

getId: function() {
  return this.get('id');
},

getName: function() {
  return this.get('name');
},

getEmail: function() {
  return this.get('email');
}
});
4

1 回答 1

0

尽管可以在我的问题的评论之一中找到相同的信息,但我被要求将其标记为答案,以方便 StackOverflow 上的其他人使用。可以在这里找到对我有用的解决方案- 请参阅我自己的答案。

于 2013-01-16T18:48:41.227 回答