3

I'm developing an Ember app with a Rails backend, using the excellent JSONAPI::Resources gem to expose my data.

I'd like to fetch records from my the backend using store.findRecord, store.query, etc. while sideloading certain relationships. JSONAPI::Resources supports this part of the spec but I can't figure out how to make Ember Data include the ?include=... parameter in the request URL.

How can I instruct Ember Data (2.2.0) to ask the backend to include relationships when fetching resources?

Max Wallace
  • 3,609
  • 31
  • 42

2 Answers2

7

If you are able, you can try out the Ember Data 2.4 beta, which includes the ds-finder-include feature flag.

This feature flag enables you to pass an options hash with an includes key.

To learn how to enable feature flags check the guide.

locks
  • 6,537
  • 32
  • 39
  • It looks like this is only enabled for `findRecord` and `findAll` -- bummer because I'm using `query` to filter on certain values. My sense is that it's not included in `query` because `query` is so low-level -- is that it? Are there any workaround you recommend? – Eli Rose Sep 28 '16 at 01:21
  • 1
    A query is a query, you can pass anything you want, including `includes`! – locks Sep 28 '16 at 08:48
4

The way I handle this is by modifying my application adapter to process includes, and then pass includes as my adapter options in my query. Right now I only handle a single include, but it shouldn't be too hard to handle an array.

app/adapters/application.js

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({

  urlForFindRecord(query, modelName, snapshot) {
    var url = this._super(...arguments);

    return this._processIncludes(url, snapshot);
  },

  urlForFindAll(query, modelName, snapshot) {
    var url = this._super(...arguments);

    return this._processIncludes(url, snapshot);
  },

  _processIncludes(url, snapshot) {
    var options = snapshot && snapshot.adapterOptions;

    if (options && options.include) {
      url = `${url}?include=${options.include}`;
    }

    return url;
  },


});

And then, in my routes model hook, I just add my adapter options.

return this.store.findRecord('myModel', params.id, {
  adapterOptions: {
    include: ['myChildModel']
  }
Mike Wilson
  • 692
  • 6
  • 12