简体   繁体   English

Backbone belongs_to has_many

[英]Backbone belongs_to has_many

Longtime Rails Dev, Backbone Noob. 长期Rails Dev,Backbone Noob。

In my rails models, a project has many tasks and a task belongs to a project.. Standard stuff. 在我的rails模型中,一个项目有很多任务,一个任务属于一个项目..标准的东西。

Trying to get a project's tasks json in a collection. 试图在集合中获取项目的任务json。

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
  url: '/projects/<dynamic_id>/tasks',
  model: ExampleApp.Models.Task
});

Every example Ive seen so far references the url as /tasks. 到目前为止,我见过的每个例子都将url引用为/ tasks。 Id like to pass a project id to the collection to get that projects tasks. 我想将项目ID传递给集合以获取项目任务。

Ive checked out Backbone Relational but not sure what the best solution is. 我已经检查了Backbone Relational但不确定最佳解决方案是什么。

Cheers 干杯

I would highly recommend using Backbone-Relational as opposed to hacking the relationship on your own. 我强烈建议使用Backbone-Relational而不是自己破解关系。 Reasons for using Backbone-Relational from personal experience: 从个人经验中使用Backbone-Relational的原因:

  • Creates forward and backward relationships, so you can get all tasks related to a project, or the project to which a task belongs 创建前向和后向关系,以便您可以获得与项目或任务所属项目相关的所有任务
  • Easy to serialize, and automatic deserizalization. 易于序列化和自动去激活。 That is, you give it a JSON and it builds out all the models and their relationships. 也就是说,你给它一个JSON,它构建了所有模型及其关系。 Very handy. 非常便利。
  • Your models remain independently defined and can use standard Backbone stuff to save/fetch without any additional work. 您的模型保持独立定义,可以使用标准的Backbone内容来保存/获取,无需任何额外的工作。
  • It can also play nicely with various Backbone extensions such as Marionette and ioBind/ioSync . 它还可以很好地与各种Backbone扩展,如MarionetteioBind / ioSync

One approach is to define url as a function and set your project_id prior to fetch() 一种方法是将url定义为函数,并在fetch()之前设置project_id

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: ExampleApp.Models.Task

    url: function() {
        return 'projects/'+this.project_id+'/tasks';
    },

    setProjectId(project_id) {
        this.project_id = project_id;
        this.fetch();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM