Sunday, April 2, 2017

How can I pass IDs for hasMany relationship using store.createRecord()?

Leave a Comment

Assume I have the following models:

// customer.js DS.Model.extend({   products: DS.hasMany('product') });  // product.js DS.Model.extend({  customer: DS.belongsTo('customer')   }); 

And I need to create a customer with a list of products by IDs(which are not yet loaded from backend), something along the lines of this:

this.get('store').createRecord('customer', {products: [1, 2, 3]});   

But this fails as the store expects the products to be an Array of DS.Model.

How can I create a record with its associations provided by IDs?

2 Answers

Answers 1

Error while processing route: index Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [1,2,3] Error

As the error states that You need to pass instance of DS.Model but you can only create instance using createRecord so you might need to do some thing like below,

    let product1 = this.store.createRecord('product',{customer:1});     let product2 = this.store.createRecord('product',{customer:2});         return this.get('store').createRecord('customer', {products:[product1,product2]}); 

Answers 2

If related records do not exist then you cannot create them on the fly just using IDs. However, you could do something like this:

let customer = this.store.createRecord('customer', {}); customer.get('products').then(function() {     customer.get('products').addObject(this.store.createRecord('product', {/* ... */})); }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment