I'm trying to create a somewhat general system in Ember where you can attach documents and comments to many different things -- for example, you might attach these things to a Post, or you might attach them to an Email.
With only one "attachment" type, I can use model-based inheritance:
// app/model/document.js
import DS from 'ember-data';
export default DS.Model.extend({
url: DS.attr('string'),
documentable: DS.belongsTo('documentable', { polymorphic: true })
});
// app/model/documentable.js
import DS from 'ember-data';
export default DS.Model.extend({
documents: DS.hasMany('document')
});
// app/model/post.js
import DS from 'ember-data';
import Documentable from './documentable';
export default Documentable.extend({
title: DS.attr('string')
body: DS.attr('string')
});
app/model/email.js, app/model/fish.js, app/model/barrel.js, etc. are pretty much the same as Post except they have attributes specific to their models.
The nice thing about this setup is that it's very easy to attach a document to something:
var post = ...; // get a single post
var document = this.get('store').createRecord('document', {
documentable: post
});
Now I want to add a commentable property so I can add comments to everything. I can't do multiple inheritance (right?), so I looked at turning Documentable into a Mixin:
// app/mixin/documentable.js
import Ember from 'ember';
export default Ember.Mixin.create({
});
// app/model/post.js
import DS from 'ember-data';
import Documentable from '../mixins/documentable';
export default DS.Model.extend(Documentable, {
title: DS.attr('string'),
body: DS.attr('string'),
documents: DS.hasMany('document')
});
but when I try to create a new document with a relationship to a post, I get an error like:
You cannot add a record of type 'post' to the 'document.documentable' relationship (only 'documentable' allowed)
Where should I go from here? One Base Class to Rule Them All (CommentableAndDocumentable?) I'd prefer to avoid adding belongsTos for each parent type to my Document model, because that breaks the polymorphic relationship on the server side (Rails application).
Many thanks!
Aucun commentaire:
Enregistrer un commentaire