Adnan
Adnan

Reputation: 934

Proper way to set multiple models on route; depending on user authentication?

I'm currently working on an Ember app and it is coming along fine but since I am new to MVC applications in general there are a lot of concepts that don't come naturally to me.

I am currently trying to return two models for my index route. I referred to another SO question (EmberJS: How to load multiple models on the same route?) for the correct method and it has worked great.

My problem is now that I need to only set one of the two models only if the user is authenticated. I am using ember-simple-auth, and currently this is what I've got:

// app/routes/index.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    if (this.get('session.isAuthenticated')) {
      var _this = this;
      this.get('store').find('user', this.get('session.uid')).then(function(user) {
        _this.set('model.entries', user.get('entries'));
      });
    }

    return Ember.RSVP.hash({
      newEntry: this.get('store').createRecord('entry', {
        body: 'Write here ...'
      })
    });
  }
});

For some reason, this does not work. After my route is loaded, the model only has the 'newEntry' property and not an 'entries' property, although the promise does get fulfilled (I put console.logs inside to prove it).

What could be happening? And is this the best way to accomplish this?

Upvotes: 0

Views: 49

Answers (1)

givanse
givanse

Reputation: 14953

There is a set of data that you always want to load, for every user. Do that in the model hook, that is actually the data for the route.

There is another piece of info that you want to add only if a condition is met (authentication). Do that in the afterModel hook.

...is provided the route's resolved model...

http://emberjs.com/api/classes/Ember.Route.html#method_afterModel

So, now you can append or remove data from the model. Or take any relevant action depending on the data that you received.

Upvotes: 1

Related Questions