mercredi 27 janvier 2016

Ember 2 simple polymorphic relations

I have a notes model that I want to attach to one of two other models, customers and suppliers.

In my database I have a foreignType and foreignId field that holds the type and the corresponding ID for the customer or supplier, something like

notes: { {id: 1, body:'bar',foreignType:'customer',foreignId:100},
         {id: 2, body:'foo',foreignType:'supplier',foreignId:100}
       }

That is, a note can be attached to a customer or a supplier.

The convention seems to be that the field be called noteType? I have seen a tutorial where the related type was nested in the JSON, rather then being at the root.

My ember models look like this:

//pods/note/model.js
  export default DS.Model.extend({
    //...
    body: DS.attr('string'),
    foreign: DS.belongsTo('noteable',{polymorphic:true})
  });

//pods/noteable/model.js (is there a better/conventional place to put this file?)
  export default DS.Model.extend({
    notes: DS.hasMany('note')
  });

//pods/customer/model.js
  import Noteable from '../noteable/model'; 

  export default Noteable.extend({ //derived from Noteable class
     name: DS.attr('string'),
     //...
   });

//pods/supplier/model.js
  // similar to customer



// sample incoming JSON
//
{"customer":{"id":2,"name":"Foobar INC",...},
 "contacts":  
    [{"id":1757,"foreignType": "customer","foreignId":2,...},
     {"id":1753,"foreignType": "customer","foreignId":2,...},
     ...],
   ...
  "todos":
     [{"id":1,"foreignType":"customer","foreignId":2,"description":"test todo"}],
  "notes":
     [{"id":1,"foreignType":"customer","foreignId":2,"body":"Some customer note "}]
}

How to set this up correctly?

My notes aren't attaching correctly to the customer model. They show up in the Data tab of the Ember Inspector, but the notes list of any customer is empty.

I can see several possibilities:

  • extend customer/supplier from DS.Model and have a property notes: belongsTo('noteable'), that would mean the belongsTo in notes isn't polymorphic, as there wouldn't be any derived classes, only Noteable itself. Not sure if ember (data) can deal with this nesting correctly.

  • extend from Noteable. what if I want to have other things like addresses or contacts, that can be related to customer or supplier?

  • create duplicate models like customernote/suppliernote, customercontact/ suppliercontact, customer/supplier/employee address. And have the backend return the filtered table/model name depending on the endpoint. I don't like to repeat myself though ....

Ember : 2.2.0
Ember Data : 2.2.1




Aucun commentaire:

Enregistrer un commentaire