Reputation: 73
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.
Upvotes: 0
Views: 1061
Reputation: 621
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({
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({
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:
links
attribute like this: `{bets: 'api/users/:uid/bets'}/api/users/:uid/bets
and return only the bets for the usercode:
import Ember from 'ember';
export default Ember.Route.extend({
model () {
const currentUser this.store.peekRecord('user', this.get('session.currentUser.uid'))
return currentUser.get('bets') // sends request to `api/users/:uid/bets`
}
});
Upvotes: 1
Reputation: 26
Are you using Ember Simple Auth? If so, your requests are sending the token which can be used to fetch the current user based on the info provided. Since it is the default behaviour to return only current users's bets, it is a good idea to keep the logic on the api side. Any other type of filter should be done with query or queryRecord methods.
Upvotes: 0