0

I am trying to create multiple posts that belong to a user using Mirage js createList facility. I have created models with corresponding relationships:

  models: {
    user: Model.extend({
      posts: hasMany(),
    }),
    post: Model.extend({
      user: belongsTo()
    })
  }

In the seeds method, I am trying to create a list of posts and allocate them to a user with this code:

  seeds(server) {

    let posts = server.createList("post", 2);

    server.create("user", {
      name: "John",
      posts: [posts],
    });

  }

Unfortunately when I hit this.get("/users"); in http request I receive a mirage error, which I understand but can't fix: Mirage: You're trying to create a user model and you passed in "model:post(1),model:post(2)" under the posts key, but that key is a HasMany relationship. You must pass in a Collection, PolymorphicCollection, array of Models, or null.

As far as I can tell I am passing an array of Models? How can I fix it, please?

J Doe
  • 132
  • 7

1 Answers1

2

So the problem was:

 posts: [posts]

This part returns an array (or collection) already:

let posts = server.createList("post", 2);

So wrapping it in another array [post] is incorrect.

Using server.create("...") we can hook onto it by putting it in array, but server.createList is already returning an array.

Correct syntax is:

  seeds(server) {

    let posts = server.createList("post", 2);

    server.create("user", {
      name: "John",
      posts: posts,
    });

  }

or even shorter:

  seeds(server) {

    let posts = server.createList("post", 2);

    server.create("user", {
      name: "John",
      posts,
    });

  }
J Doe
  • 132
  • 7