Self association, polymorphic associations guide


#1
App.Employee = DS.Model.extend({
  manager: DS.belongsTo('employee'),
  assistants: DS.hasMany('employee', { inverse: 'manager' })
 })

This does not work. I am using ember data 1.0.0-beta.5. Getting an error of no model manager was found. All the stackoverflow answers and guides are outdated. Could someone guide me on this one? And also add on how to go about polymorphic associations? At least a pointer would be really helpful.

** What i did**

    App.Employee = DS.Model.extend({
    /* employee attributes*/ 
    })
App.Assistant = App.Employee.extend({
  manager: DS.belongsTo('manager')
})
    App.Manager = App.Employee.extend({
        assistants: DS.hasMany('assistant')
)}

This is definitely not the right approach, please guide.


#2

have you tried setting the inverse on manager? Generally speaking you need the inverse to be explicitly declared on both ends of the relationship. Since there is only one belongsTo and only one hasMany, you may also not need to declare the inverse at all, or it may work only declaring it on manager instead of on assistants. (this sort of super self-referential model is not one I’ve attempted so I would be curious to know what other bugs / solutions you encounter.)

Your extend solution is probably the right one, definitely so if managers are never assistants.


#3

No inverse on manager does not solve this. It raises an error no manager model was found. One workaround was

App.Employee = DS.Model.extend({
   manager: DS.belongsTo('employee', { inverse: 'assistants' } ),
   assistants: DS.hasMany('employee', { inverse: 'manager' })
});
App.Assistant = App.Employee.extend({});
App.Manager = App.Employee.extend({});

Now inverse does not seem to work if there is no model manager, assistant.


#4

Are you absolutely sure that the “no manager model was found” error was raised by the presence of the “inverse” definition? Because inverse should not be looking up a manager model, period, it should be looking up ‘App.Employee.manager’. Here is a working JSbin: http://jsbin.com/OnisiwAP/18#/employees


#5

Thank you so much :slight_smile: I think the issue might be with the adapter, i use _ams (active model serializer adapter) that raises that error of no model found.