Seeding Relations in Ember Mirage with Factories

When we are working on an EmberJs project, for all but the most trivial applications, we like to mock API calls so we can develop the UI of our application independently of the back end. Enter in Ember-cli-Mirage. a really essential library maintained by Sam Selikoff.

We’re not going to deep dive into all of the features that Ember-Mirage offers, but rather point out a feature thats really handy when creating object relations in your mock api. When you use a factory to populate your database, you can create the data relation right in the factory.

Take for example the idea of posts and comments. Lets imagine in your system that one post has many comments. You’ve created a model for your Post object. Ember-cli-mirage now supports models with relations, btw:

(Note that I am leaving out any attributes in these examples, only the relations. Of course your post is going to have authors, etc)

import { Model , hasMany } from 'ember-cli-mirage';

export default Model.extend({

And you also have created the comment object:

import { Model, belongsTo } from 'ember-cli-mirage';

export default Model.extend({

Now that we have established the relationships of our objects using the models, lets look at the factories that will create them, specifically the post factory. What we want to do, is any time the post factory runs, we want to mock up a bunch of comments to go along with it. We can do this with the afterCreate() hook in the factory itself:

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

export default Factory.extend({

  afterCreate(comment, server) {
     server.createList('comment', 10 ,{post});


In the afterCreate hook above, we are creating 10 comments, and attaching the postId to the comment. We can then run Server.createList(‘post’,10); in our /scenarios/default.js file. For each Post, the factory will then generate the complimentary comments.

About Curious Minds
We are a web development firm in New York and Chicago, providing development resources and consulting for websites and mobile apps since 2004.