【发布时间】:2016-05-04 19:10:07
【问题描述】:
我有一个笔记模型,我想将它附加到其他两个模型(客户和供应商)之一。
在我的数据库中,我有一个 foreignType 和 foreignId 字段,其中包含客户或供应商的类型和相应 ID,例如
notes: { {id: 1, body:'bar',foreignType:'customer',foreignId:100},
{id: 2, body:'foo',foreignType:'supplier',foreignId:100}
}
也就是说,可以为客户或供应商附加注释。
约定似乎是该字段被称为noteType? 我见过tutorial,其中相关类型嵌套在 JSON 中,而不是位于根目录中。
我的 ember 模型如下所示:
//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 "}]
}
如何正确设置,即 Ember 期望什么?
我的笔记没有正确附加到客户模型上。它们显示在 Ember Inspector 的“数据”选项卡中,但任何客户的备注列表都是空的。
我可以看到几种可能性:
从 DS.Model 扩展客户/供应商并拥有属性
notes: belongsTo('noteable'),这意味着注释中的 belongsTo 不是多态的,因为不会有任何派生类, 只有 值得注意 本身。不确定 ember(数据)是否可以正确处理这种嵌套。从值得注意的扩展。如果我想要其他可以与客户或供应商相关的信息,例如地址或联系人,该怎么办?
创建重复模型,例如 customernote/suppliernote、customercontact/suppliercontact、customer/supplier/employee address。并让后端根据端点返回过滤后的表/模型名称。不过我不喜欢重复自己......
余烬:2.2.0
灰烬数据:2.2.1
【问题讨论】:
标签: ember.js polymorphism