Mirage and Polymorphic models

Hello, Dear Emberistas! :hamster:,

I try to understand how to work in Mirage with polymorphic models, I would appreciate any help with this.

My models:

// app/models/order.js

import Model from 'ember-data/model';
import { belongsTo } from 'ember-data/relationships';

export default Model.extend({
  product: belongsTo('product', { polymorphic: true })
});
// app/models/product.js

import Model from 'ember-data/model';
import { hasMany } from 'ember-data/relationships';

export default Model.extend({
  orders: hasMany('order', { inverse: 'product' }),
});
// app/models/product/vehicle/car.js

import Product from '../../product'
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';

export default Product.extend({
  description: attr('string', { defaultValue: '' }),
  model: attr('string', { defaultValue: '' }),

  pictures: hasMany('image')
});
// app/models/product/appliances/refrigerator.js

import Product from '../../product'
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';

export default Product.extend({
  brand: attr('string', { defaultValue: '' }),
  description: attr('string', { defaultValue: '' }),

  pictures: hasMany('image')
});

Let me know any idea how to mock it in Mirage.

Denis

Hi Denis, this should work in mirage basically the same way it would on the front-end. You should be able to create a… let’s say fridge and then attach it to an order, something like this:

let fridge = server.create('product/appliances/refrigerator', { ... });
let order = server.create('order', { product: fridge });

Mirage should take care of the rest automatically. I will note though that the nested model structure may cause you resolver issues, I haven’t personally tried anything like that (at least that I remember) but you may have to fully qualify the model name like I did above, and I’m not sure how mirage will react to that.

Also you’ll want to use JSON API Adapter/Serializer, or at least a custom one that returns record types from the API. Polymorphic types don’t really work if the payloads don’t contain the record types.

1 Like