I'm using Ember 1.13.2 and Ember-data 1.13.4
I'm trying to find the out the type of relationship that a model has. Take the following example model.
// my post model
export default DS.Model.extend({
author: DS.belongsTo('author'),
comments: DS.hasMany('comment')
});
How can I check in my code if comments
is a hasMany or belongsTo relationship?
At the moment I have worked out two solutions that work, but they feel a bit messy to me and I'm sure there must be a better way.
one way that works is this
var relationship = post.get(relationshipName); // relationshipName = 'comments'
if ( relationship.constructor.toString().indexOf('Array') !== -1 ) {
relationshipType = 'hasMany';
}
else if ( relationship.constructor.toString().indexOf('Object') !== -1 ) {
relationshipType = 'belongsTo';
}
another way that works
var relationship = post.get(relationshipName); // relationshipName = 'comments'
if (relationship.get('@each')) {
relationshipType = 'hasMany';
}
else {
relationshipType = 'belongsTo';
}
they both work, but they both feel a bit clunky to me and I don't know how reliable they are.
So the question is, which is the more reliable method?.. or is there a better way?
post.get('comments')
you are given the values - not a special relationship object. Depending on your code I'd suggest moving the code to the post model itself, like:post.doSomethingWithAllBelongsTo()
and add that method to your post model. There you can access all relationships of that model withthis.eachRelationship
, where you can access the kind. – enspandi