bfcoder
bfcoder

Reputation: 3132

Searching Ember data async hasMany ids without loading all the id records

I am trying to search through several thousand records for a particular record. I have loaded a User model and it has several thousand Shipments that are async. In other words I have the serializer send down shipment_ids with the user model.

App.User = DS.Model.extend({
  shipments: DS.hasMany('shipment', { async: true })
});

I want to search through all those ids to see if a particular record's id is among them. However I don't want to go to the api and load each and every single record. I just want to be able to search through the shipment_ids.

I have a jsbin that showcases it loading all the records. How do I change this so it doesn't make any api calls for a shipment and still finds the specific record?

Instead of doing

this.get('shipments').any(function(shipment){
  return shipment.get('id') === "10124";

there has to be a way to go through only the ids, no?

Thanks!

Upvotes: 1

Views: 1623

Answers (3)

Envek
Envek

Reputation: 4714

Since Ember Data 2.3 you can use this code:

// get all ids without triggering a request
var commentIds = post.hasMany('comments').ids();

See http://emberjs.com/blog/2016/01/12/ember-data-2-3-released.html for details.

Upvotes: 2

gordonc
gordonc

Reputation: 532

The solution described in "Get belongsTo ID without fetching record" seems to work as of Ember Data 1.0.0-beta.10. Briefly, you can do the following to access the underlying

modelInstance.get('data.belongsToRelation.id');

Presumably you can also do this (though I have not tested it):

modelInstance.get('data.hasManyRelation');

Original Answer (DO NOT USE):

I have accomplished this on a belongsTo by adding a second model field for the id. My example:

App.User = DS.Model.extend({ group: DS.belongsTo('group', { async: true }), groupId: DS.attr('number') });

So maybe you can do this?

App.User = DS.Model.extend({ shipments: DS.hasMany('shipment', { async: true }), shipmentIds: DS.attr('array') });

You will need to add an array transform in app/transforms/array.js (assuming you use ember-cli)

import DS from 'ember-data';

var ArrayTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } });

export default ArrayTransform;

Let me know if it works as I probably will need to something similar in my app soon.

Upvotes: 2

bfcoder
bfcoder

Reputation: 3132

This hack is very smelly but it's the only way I have found. And it is to search with _data

this.get('content._data.shipments').any(function(shipment){
  return shipment.get('id') === "10124";
});

It won't make any api calls. But there has to be a more acceptable method that won't be prone to breakage when updating Ember.

Here is an updated jsbin to show this. Does anyone have a better solution?

Thanks!

Upvotes: 2

Related Questions