samedi 29 octobre 2016

Ember Data persisting model with hasMany relationship and fetching json

I am creating an Ember app using Ember Data and firebase. I have two models, a parking lot and a parking space. The lot has a hasMany relationship with the parking-space.

This is the lot model:

import Ember from 'ember';
import DS from 'ember-data';

export default DS.Model.extend({

    name: DS.attr('string'),
    spaces: DS.hasMany('parking-space'),
    queue: DS.hasMany('vehicle'),
    isFull: Ember.computed('spaces',function() {
        let availableSpaces = this.get('spaces').filter((space) => {
            return space.vehicle == null;
        });
        return availableSpaces.length === 0;
    })

});

This is the parking-space model:

import Ember from 'ember';
import DS from 'ember-data';

export default DS.Model.extend({

    lot: DS.belongsTo('lot'),
    size: DS.attr('string'), // small, medium, large
    vehicle: DS.belongsTo('vehicle'),
    isEmpty: Ember.computed.empty('vehicle')

});

This is the code to add a new parking lot with a space:

//Create new lot


    let newLot = store.createRecord('lot',{
            name:'Rainmaker Parking Lot',
            spaces: [],
            queue: []
        });
        newLot.save().then(() => {
            //Create spaces
            store.createRecord('parking-space',{
                lot: newLot,
                size: 'small'
            }).save();
            return 'success';
        });

Initially, this code was inserting a record in each table in firebase but the lot table didn't have the spaces relationship. The parking-space did contain the lot relationship though. To remedy this, i modified the lot serializer:

import DS from 'ember-data';

export default DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin).extend({
    attrs: {
        spaces: {
            serialize: 'records', 
            deserialize: 'records'
        }
     }
});

This is now inserting the records the way that I want them, having the spaces embedded in the lot object in firebase. However, now, when i try to retrieve the list of lots, i'm getting an error: Cannot read property 'id' of null TypeError: Cannot read property 'id' of null

This is the code i'm using to fetch the data:

let store = this.get('store');
return store.findAll('lot');

Any ideas as to why this is happening? I'm guessing it has to do with my deserializer settings. Any help would be appreciated as I am new to ember data.

Thanks,




Aucun commentaire:

Enregistrer un commentaire