javascript - 如何在 Mirage js 中为具有多态一对一关系的模型提供种子?

标签 javascript ember-cli-mirage mirage miragejs

这只是一个例子,我知道您通常会有多个评论,但为了这个例子,我们假设我们有

以下型号:

 models: {
    blogPost: Model.extend({
      comment: belongsTo(),
    }),

    picture: Model.extend({
      comment: belongsTo(),
    }),

    comment: Model.extend({
      commentable: belongsTo({ polymorphic: true }),
    }),
  },

以及以下工厂:

  factories: {
    blogPost: Factory.extend({
      title: "Whatever",
      withComment: trait({
        comment: association(),
      }),
  }),

现在尝试使用以下方式为服务器提供种子时:

seeds(server) {
  server.create("blogPost", "withComment");
}

它确实播种了它,但是在检查 console.log(server.db.dump()); 时可评论为空... commentableId: null .

enter image description here

为什么?

编辑:

这是一个棘手的问题。我变了

comment: Model.extend({
  commentable: belongsTo({ polymorphic: true }),
}),

至:

comment: Model.extend({
  blogPost: belongsTo({ polymorphic: true }),
}),

只是为了看看 commentable部分导致了问题。这次我得到了一个不同的错误: Mirage: You're using the association() helper on your comment factory for blogPost, which is a polymorphic relationship. This is not currently supported."

因此,目前无法使用 association()关于多态关系。我希望这在文档中宣布...

尽管如此,即使没有速记,我也找不到播种它的方法 association() .

最佳答案

这是一种方法:

import { Server, Model, Factory, belongsTo, trait, association, RestSerializer } from "miragejs"

export default new Server({
  serializers: {
    blogPost: RestSerializer.extend({
      include: ['comment']
    }),
  },

  models: {
    blogPost: Model.extend({
      comment: belongsTo(),
    }),

    picture: Model.extend({
      comment: belongsTo(),
    }),

    comment: Model.extend({
      commentable: belongsTo({ polymorphic: true }),
    }),
  },
  
  factories: {
    blogPost: Factory.extend({
      title: "Whatever",
      withComment: trait({
        afterCreate(blogPost, server) {
          server.create('comment', {
            commentable: blogPost
          });
        }
      }),
    })
  },

  seeds(server) {
    server.create("blog-post", "withComment");
    console.log(server.db.dump())
  },
  
  routes() {
    this.resource('blog-post')
  }

})

这是有效的 REPL:http://miragejs.com/repl/v1/144

如果您单击“数据库”选项卡,然后单击“评论”,您应该会看到引用 blog-post:1 的多态 ID。

您还可以向 /blog-posts 发送 GET,您应该会看到包含评论,或者向 /comments 发送 GET 并看到多态 可评论包括在内。

关于javascript - 如何在 Mirage js 中为具有多态一对一关系的模型提供种子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556674/

相关文章:

javascript - 基于概率的变体选择

ember.js - Ember DS.Store.findAll() 返回空集合

ember.js - 如何在 ember-cli-mirage 中创建关系?

javascript - Ember.js ajax POST 请求未通过 Mirage

xen - 如何构建 Mirage OS 的 Xen unikernel

javascript - 根据更改事件填充选择下拉列表

javascript - 滚动事件触发多次,但我需要它每次滚动触发一次

ocaml - 是否可以在ocaml cohttp或conduit中获取远程IP地址?

javascript - javascript 中的 DRY 用于动态字段

javascript - Ember : Cannot access model data in controller/template