【问题标题】:Backbone: Using a form to save model, as well as model relationship into the databaseBackbone:使用表单保存模型,以及模型关系到数据库
【发布时间】:2012-06-06 23:38:50
【问题描述】:

我一直在为我的一个 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');
}
});

【问题讨论】:

  • 您需要提供一些代码并准确确定问题所在,才能得到一个体面的答案。
  • 你可以在link找到适合我的解决方案。
  • 您应该在此处发布该链接作为答案并接受它作为解决方案,因为人们通常不阅读 cmets。他们在谷歌上找到了这个问题,打开这个页面,发现没有找到解决方案。这是 StackOverflow 的方式 :)
  • 可以找到对我有用的解决方案 [这里][1] - 请参阅我自己的答案。 [1]:stackoverflow.com/questions/11130856/…

标签: database forms view backbone.js relationship


【解决方案1】:

虽然可以找到与我的问题相同的信息之一,但我被要求将其标记为答案,以方便 StackOverflow 上的其他人。可以找到对我有用的解决方案 here - 请参阅我自己的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2012-12-18
    • 2021-06-28
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多