user2239595 user2239595 - 4 days ago 4
Javascript Question

Getting records by attribute in ember

In my application route I get the current session and user.

/routes/application.js

import Ember from 'ember';

export default Ember.Route.extend({

beforeModel: function() {
return this.get('session').fetch().catch(function() {});
},
model () {
return this.store.findRecord('user', this.get('session.currentUser.uid'));
}
});


My models are set up like so:

/models/bet.js

import DS from 'ember-data';

export default DS.Model.extend({
created: DS.attr('date'),
user: DS.belongsTo('user', { async: false })
});


/models/user.js

import DS from 'ember-data';

export default DS.Model.extend({
email: DS.attr('string'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
bets: DS.hasMany('bet', { async: true })
});


In my /bets route I'd like to load only the bets where
user == session.currentUser.uid
or a similar way to get only the
bets
that
belongTo
the current user.

I've tried finding the best way to do this without results.

Answer

The niave approach is to filter all bets to just the ones you want. An api based solution could be 1) Use query params on the request to the server, 2) nested urls like /users/2/bets. In either case you'd have to implement this on the server.

Example 1) Filter

import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    return this.get('session').fetch().catch(function() {});
  },
  model () {
    return this.store.findAll('bet').then((bets) => {
      const currentUserId = this.get('session.currentUser.uid')
      return bets.filter((bet) => {
        return bet.get('user.id') === currentUserId
      })
    });
  }
});

Example 2) Query. Your server will have to take the res

import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    return this.get('session').fetch().catch(function() {});
  },

  model () {
    return this.store.query('bet', {
      userId: this.get('session.currentUser.uid')
    })
  }
});

Example 3) Nested Attributes. In order to do this you need 2 things:

  1. a user comes with a links attribute like this: `{bets: 'api/users/:uid/bets'}
  2. Your server will have to be able to respond to the request /api/users/:uid/bets and return only the bets for the user

code:

import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    return this.get('session').fetch().catch(function() {});
  },

  model () {
    const currentUser this.store.peekRecord('user', this.get('session.currentUser.uid'))
    return currentUser.get('bets') // sends request to `api/users/:uid/bets`
  }
});
Comments