Rudi Werner
Rudi Werner

Reputation: 109

ember data model with id from created record howto?

I am creating an Ember Data model with the following elements. Is it possible to set the equalTo in invoiceRows to the id of the newly created invoice?

model: function() {
  return Ember.RSVP.hash({
    parameter: this.store.findRecord('parameter',1),
      invoice: this.store.createRecord('customerinvoice',{
        order_reference : '',
        ordernr_bol: '',
        payment_method: '',
        invoice_type: '',
        company_name: '',
        customer_city: '',
        customer_country: '',
        customer_email: '',
        customer_first_name: '',
        customer_name: '',
        customer_phone: '',
        customer_phone_mobile: '',
        customer_postal_code: '',
        customer_street_nr: '',
        customer_vat_number: '',
    }),
    customers: this.store.findAll('customer'),
    invoiceRows: this.store.query('customerinvoicerow', {
      orderBy: 'id_cust_invoice_fb',
      equalTo: **THIS MUST BE ID OF CREATED INVOICE ???????**
    }),
    products: this.store.findAll('product')
  });
}

Upvotes: 1

Views: 475

Answers (1)

nem035
nem035

Reputation: 35491

Without looking at the code for the store and the serializer, one thing I can suggest is to create the record first, then extract the id from it and use it for the remaining promises:

model: function() {
  // create the invoice first
  const invoice = this.store.createRecord('customerinvoice', { /* ... */ });

  // then create the promises
  return Ember.RSVP.hash({
    parameter: this.store.findRecord('parameter', 1),
    invoice, // pass the invoice here
    customers: this.store.findAll('customer'),
    invoiceRows: this.store.query('customerinvoicerow', {
      orderBy: 'id_cust_invoice_fb',
      equalTo: invoice.get('id') // Extract the ID here
    }),
    products: this.store.findAll('product')
  });
}

Another thing, instead of creating all those customerinvoice properties initialized to empty strings, you can define default values for ember models which will be added if properties are omitted:

export default Model.extend({
  order_reference: attr('string', { defaultValue: '' })
  // rest of the properties and their default values...
});

Then you can just create a record without passing anything.

this.store.createRecord('customerinvoice');

Upvotes: 1

Related Questions