如何在 Mirage js 中播种具有多态一对一关系的模型?

How to seed models with polymorphic one to one relationship in mirage js?

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

以下型号:

 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.

为什么?

编辑:

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

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()。我希望这在文档中宣布...

即使没有 shorthand 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

您也可以将 GET 发送到 /blog-posts,您应该会看到注释已包含在内,或者将 GET 发送到 /comments 并会看到包含多态 commentable

此特定错误:

You're using the association() helper on your comment factory for blogPost, which is a polymorphic relationship. This is not currently supported."

以这种方式为我解决了: // mirage/factories/comment.js

之前:

import { association, Factory } from 'ember-cli-mirage';

export default Factory.extend({
  blogPost: association()

之后:

import { association, Factory, trait } from 'ember-cli-mirage';

export default Factory.extend({
  blogPost: trait({
    receiver: 'blogPost',
    blogPost: association()
  }),