How to add a filtered array to a model


#1

I have a list of products I am rendering as a component.

This is my template

<p>{{product.name}}</p>
<p>{{product.description}}</p>
<p>{{product.price}}</p>
<p>{{product.productCategory.id}}</p>
{{#product-line-item product.lineItems}}
{{/product-line-item}}

I am trying to pass a filtered array (product.lineItems) to a component so I can indicate the quantity for each product that is in the cart. What I am trying to do in the model seems incorrect.

Here is my attempt at creating an array on the product model for lineItems that belong to that product:

export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({
      products: this.store.findAll('product'),
      productCategories: this.store.findAll('productCategory'),
      lineItems: this.store.queryRecord('lineItem', { user_id: this.get('session.secure.user_id') })
    }).then(function (model) {
      model.products.forEach(function(product){
        product.lineItems = [];
        model.lineItems.forEach(function(lineItem) {
          if (lineItem.productId === product.id) {
            product.lineItems.pushObject(lineItem);
          }
        })
      });
      return model
    });
  }
});

Firstly, each product ends up having an empty lineItems array.

Secondly this doesn’t feel right. Am I barking up the wrong tree?


#2

Your life would be easier with Ember Data. You would be able to define relationships easily; see http://guides.emberjs.com/v2.0.0/models/defining-models/#toc_defining-relationships.

Basic idea is (in regards to your code):

  • add a relation Product <=> LineItem
  • add a relation User <=> LineItem
  • execute a (pseudo-code) currentUser.get("lineItems").mapBy("products").reduce((m, a)=> m.concat(a))