Filter Ember Data Store by Related Model's ID


#1

I’ve got 2 models – tasks and actions – in a belongsTo <–> hasMany.

/app/model/action.coffee
  ...
  task: DS.belongsTo('task')
  ...

/app/model/task.coffee
  ...
  actions: DS.hasMany('actions')
  ...

In the route, I’m trying to use peekAll and filter to determine if I’ve already grabbed a list of actions for a specific task from the back-end. If I have, I used the cached data; if not, I hit the back-end:

/app/actions/route.coffee
model: ->
  task = @modelFor(@get('routeName').split('.')[0..-2].join('.')).task
  query = {root: 'actions', task_id: task.id}
  actions = @store.peekAll('action').filter (action) ->
    action.get('task.id') == task.id

  if actions.get('length')
    @setNetworkEntities(actions)
    @store.query('action', query)
    return {
      actions: actions
      columns: @get('columns')
    }
  else
    @store.query('action', query).then (actions) =>
      @setNetworkEntities(actions)
      return Ember.RSVP.hash
        actions: actions
        columns: @get('columns')

The problem is in the filter step:

actions = @store.peekAll('action').filter (action) ->
  action.get('task.id') == task.id

when I get('task.id') Ember Data is making a network call and hitting the back-end. Is there a way to get the task.id? It must be stored on the action but I can’t find a way to access it without hitting the wire.

Thanks!


#2

You can check out the references api http://emberjs.com/blog/2016/03/13/ember-data-2-4-released.html#toc_code-ds-references-code


#3

Thanks @remkoboschker. That looks like exactly what I need :slight_smile: