mercredi 17 février 2016

Displaying a belongsTo relationship in Ember template

I've read that Emberfire does not persist data on the hasMany side, only the belongsTo. For example, I have some code here:

// Note model
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  customer: DS.belongsTo('customer', { inverse: 'notes' })
}); 

// Customer model
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  address: DS.attr('string'),
  phone: DS.attr('string'),
  isSuspended: DS.attr('boolean', {defaultValue: false}),
  notes: DS.hasMany('note', { inverse: 'customer' }),
  trips: DS.hasMany('trip'),
  vehicles: DS.hasMany('vehicle')
});

When I call addNote on a particular customer, it does work, and I can see it on Firebase, like this. You can see that under the Note model, it is saved with the correct customer id, but on the Customer side, it is not showing.

My question is then, how do I display the data on a template (.hbs) file? Currently I have something like this:

  <table class="table table-striped">
    <tbody>  
        {{#each model.notes as |note|}} 
        <tr>
            <th>{{note.name}}</th>
        </tr>     
      {{/each}}
    </tbody>
  </table>

It doesn't show on localhost of course, because there is no Customer.notes in Firebase. I don't know how to display the data because I am using the 'model' keyword.

What can I do so that the correct notes for a certain customer is displayed on their respective dynamic routes?

Here is my code for addNote just in case:

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return this.store.createRecord('note');
      },

    actions: {

        addNote(newNote) {
            let customer = this.modelFor('customer');
            customer.get('notes').pushObject(newNote);
            newNote.save().then(() => {
                    this.transitionTo('customer.notes', customer);
                });
            }
        }

});

Thank you. :)




Aucun commentaire:

Enregistrer un commentaire