How to find relationships of any arbitrary ember-data model?


#1

Is there a way to programmatically determine the relationships of an arbitrary ember-data model?

For example:

# basket
import DS from 'ember-data';
export default DS.Model.extend({
  fruits: DS.hasMany('fruit');
});

Is there an Ember way to get to fruits without knowing the model was basket beforehand?


#2

What are you trying to achieve?

Do you just want to load fruit into the store independently of basket? If so you could load a bunch of models on a single route with RSVP.hash


#3

Here’s what I’m trying to achieve: Regardless of incoming model, if it has relations, I want to know about it and iteration through those relations. So given the example above, it could be a basket of fruits, a container of vehicles or a handful of gems. I don’t care what the model is; I just want to know if the said model has hasMany or belongsTo relations within itself.


#4

IF what you want is for Basket to have many items, and those items could be fruit, meat, etc, you are looking for a polymorphic relationship.

import DS from 'ember-data';
export default DS.Model.extend({
  items: DS.hasMany('item', { polymorphic: true });
});

http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data (search for ‘polymorphic’)

IF you literally mean you want to hit an API endpoint, and it’s going to send you random model definitions that you will parse client-side then I’m pretty sure Ember Data will not help you. I’m sure it can be done, in fact, I could probably think of how to do it but it falls way outside of what Ember data was designed to do, which is to provide a useful abstraction layer for fetching data through standard RESTful APIs.


#5

Hey, sorry. I think the way I explained it might have caused some confusion. And thanks for your replies.

Somewhere else in the application, a model is passed as an argument like to a method to be processed like so:

...
  fetchContent: function(model) {
    // go through the model's relationships, whatever they are, access their content
    let relationships = model._internalModel._relationships;
    relationships.forEach(function(relationship) {...});
  }
...

The obvious caveat is that the fetchContent method above doesn’t know what the model is going to be ahead of time. And that model could be a number of different types of models. So I can’t just blindly say model.get('fruits') because model might not be basket.

So the original question was: Instead of accessing an unknown number and unknown type of relationships by using model._internalModel._relationships, is there a more Ember way to do this?

Thanks.