hasMany relationship not workling with inherited model

Hi,
first, explaining the models:

  1. A Parent model that have a “hasMany” relationship
  2. A Child model
  3. The Address model ( the “hasMany”) which has a “belongsTo” Parent.

And, at some point in the application, I receive a Child payload with the addresses, but, for some reason I don’t know (yet), the addresses are not binding to the Child model properly.

It’s something like this:

// person.js
export default DS.Model.extend({
    // . . .
    addresses: DS.hasMany('address', {async: false})
})

// customer.js
export default Person.extend({
    // . . .
})

// address.js
export default DS.Model.extend({
    person: DS.belongsTo('person')
})

The addresses are in the payload, but Customer model does not have the addresses in it.

What I am doing wrong?

Thanks!

This is just a guess at first glance but I think the problem is the relationship inverses. They can be tricky because they are implicit (I personally like to always specify them explicitly). If you were to explicitly define them it would be easier to see that your ‘person’ model is related to ‘address’, and address is related back to ‘person’, not ‘customer’.

My guess is you’d need to make the relationship on the “address” model:

person: DS.belongsTo('person')`

a polymorphic relationship:

person: DS.belongsTo('person', { polymorphic: true })

But this will probably only work if your backend sends type information. If you’re unable to do that you could always try setting the inverses to null but I can’t remember if that works or not offhand.

1 Like

Thanks! Expliciting the inverses I could see why the relations wasn’t binding correctly. I had to declare another addresses property on the Customer Model, and create a customer property in the Address Model, and then adding the inverses. like this:

// person.js
export default DS.Model.extend({
    // . . .
    addresses: DS.hasMany('address', {async: false, inverse: 'person'})
})

// customer.js
export default Person.extend({
    // . . .
    addresses: DS.hasMany('address', {async: false, inverse: 'customer'})
})

// address.js
export default DS.Model.extend({
    person: DS.belongsTo('person', {inverse: 'addresses'})
    customer: DS.belongsTo('customer', {inverse: 'addresses'})
})

Looks like a charm! Thanks!

1 Like