naseem
naseem

Reputation: 13

Ember rendering multiple models

I want to render multiple models into the same route. The data is coming from a DRF api in JSON format. I need to access the data in the template separately.

Upvotes: 0

Views: 54

Answers (2)

Djamel
Djamel

Reputation: 818

Just use Ember.RSVP hashes. It's quite simple, just import RSVP like so :

import RSVP from 'rsvp';

And then you load the model like so

model() {
return RSVP.hash({
  user: this.store.findAll('user'),
  model2: this.store.findAll('model2')
 });
}

And then when you want to access to the different two model in your template for example just do : model.model2

So for example if the first loaded model is a user do model.user.firstObject.firstName or like so in your template.hbs {{model.user.firstObject.firstName}}

You will find some documentation about it here : Ember RSVP documentation

Upvotes: 1

user7474631
user7474631

Reputation:

The things you have to keep in mind that

  1. You are using a DRF backend (so you must use Ember DRF Adapter and Serializer), for more information use this link. Make sure that adapter and model has the same name.

  2. You've to load more than one model into the route

so here you can make use of RSVP hash,

example:

import Route from '@ember/routing/route';
import hash from 'rsvp'

export default Route.extend({
    model: function() {
        return hash({
            post1: this.store.findAll('model1');
            post2: this.store.findAll('model2');
        });   
    },
    setupController(controller, model) {
        this._super(...arguments);
        Ember.set(controller, 'post1', model.post1);
        Ember.set(controller, 'post2', model.post2);
    }
});

Now in the template.hbs you can access this model as follows,

{{#each post1 as |people|}}
  <p>{{people}}</p>
{{/each}}
{{#each post2 as |user|}}
  <p>{{user}}</p>
{{/each}}

Upvotes: 0

Related Questions