Backbone:使用表单来保存模型,以及模型与数据库的关系

时间:2012-06-06 23:38:51

标签: database forms view backbone.js relationship

我一直在使用我的一个Backbone视图中的表单。该表单应该保存项目模型的信息(例如项目名称,项目描述,项目成员)。虽然项目特定信息在没有任何问题的情况下保存到相应的数据库表中,但我没有设法将项目用户关系保存在联合数据库表中(projects_users,包含两个实体的相应ID)。可以添加到表单中的项目的用户已经存在于数据库中,因此不需要将任何内容添加到用户数据库表中。

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

Backbone-relational

Model relationships in Rails and 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');
}
});

1 个答案:

答案 0 :(得分:0)

虽然可以找到相同的信息作为我的问题的评论之一,但我被要求将其标记为答案,以便让StackOverflow上的其他人轻松。可以找到适合我的解决方案here - 请参阅我自己的答案。

相关问题