Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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

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

like image 649
Abdulaziz Avatar asked Mar 22 '17 23:03

Abdulaziz


2 Answers

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]});
like image 59
Ember Freak Avatar answered Nov 15 '22 11:11

Ember Freak


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', {/* ... */}));
});
like image 36
user4426017 Avatar answered Nov 15 '22 11:11

user4426017