Search code examples
arraysember.jscontrollercomputed-properties

Can't call forEach on model hash in controller


I have a route called tickets which has it's model setup like so

model() {
  return Ember.RSVP.hash({
    event: null,
    tickets: null
  });
},
actions: {
  didTransition(){
    if(!this.controller.get('model.length')){
      new Ember.RSVP.hash({
        event: this.modelFor('events.event'),
        tickets: this.store.query('ticket',{user_id:this.get('user.user.user_id'),event_code:this.modelFor('events.event').get('event_code')})
      }).then((hash)=>{
        if(!hash.tickets.get('length')){
          this.controller.set('noTickets',true);
        }
        this.controller.set('model',hash);
      });
    }
  }
}

The template manages to loop over these model.tickets just fine in a {{#each}} block

In my controller I'm attempting to setup a groupBy computed, but in my computed is where I get the error

ticketsByPurchase: Ember.computed('model.tickets.[].ticket_purchase_code',function(){
    let tickets = this.get('model.tickets');
    tickets.forEach(function(ticket){
      console.log(ticket);
    });
  })

Solution

  • Try guarding against the model.tickets being iterated over, with something like this in the computed property:

    if(!tickets){
      return Ember.A()
    }else{
      //your forEach code here
    }
    

    or this in your route:

      }).then((hash)=>{
        if(!hash.tickets.get('length')){
          this.controller.set('noTickets',true);
          hash.tickets = Ember.Array([])
          this.controller.set('model',hash);
        }else{
          this.controller.set('model',hash);
        }
      });