Ember.js:使用belongsTo相同类型继承模型

时间:2015-06-24 14:33:35

标签: ember.js ember-data

我想使用像这样的自引用模型

//models/instanceable-element.js
import DS from 'ember-data';

export default DS.Model.extend({
  instanceName: DS.attr('string'),
  parentElement: DS.belongsTo('instanceable-element', {async: true})
});


//models/basic-element.js
import DS from 'ember-data';
import InstanceableElement from './instanceable-element';

export default InstanceableElement.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
});


//models/alpha.js
import DS from 'ember-data';
import BasicElement from './basic-element';

export default BasicElement.extend({
  someMember: DS.attr('string')
});

视觉:

                +-------------+                     
                |             |                     
                |             |                     
                |             ++parentElement       
+--------------------+        |belongsTo("sameType")
|InstanceableElement |        |                     
|                    <--------+                     
|                    |                              
|                    |                              
+---------^----------+                              
          |                                         
          |                                         
          |inherit                                  
          |                                         
          |                                         
+--------------------+                              
|  BasicElement      |                              
|                    |                              
|                    |                              
|                    |                              
+---------^----------+                              
          |                                         
          |inherit                                  
          |                                         
+--------------------+                              
|  Alpha             |                              
|                    |                              
|                    |                              
|                    |                              
+--------------------+                              

这个想法是每个alpha(以及继承自basic-elment-&gt; instanceable-elment的其他模型)都可以拥有相同类型的子项,例如alpha可以将alpha作为父级。 所以现在,当我使用alpha.get('parentElement')从alpha请求父元素时,RESTAdaper会调用类似的东西:

GET http://localhost:4200/api/instanceableElements/3 404 (Not Found)

但我希望请求转到

GET http://localhost:4200/api/alphas/3

我该怎么做?

1 个答案:

答案 0 :(得分:1)

你正试图做一些类似于多态的事情。您已经使用模型超类找到了一个简单实现的基本问题。您可以尝试使用Ember Data的内置多态性支持,但它很不稳定。您可以阅读有关多态性的文档并尝试弄清楚。例如,您的服务器必须以特殊方式返回关联,如

parent: { type: 'alpha', id: 123 }

但是我不会预测走这条路会会有多大的快乐。除非你想花费更多的时间,否则你最好放弃一个值得称赞的目标,即在超类中优雅地封装父关系,并在每个类中放置特定于类的父母。