How do I programmatically create several records with createRecord?

I want to do the following:

this.get(‘store’).createRecord(‘product’,
[
{ id: 1, name: ‘Apple’ },
{ id: 2, name: ‘Grapes’ },
{ id: 3, name: ‘Strawberry’ },
{ id: 4, name: ‘Banana’ },
{ id: 5, name: ‘Orange’ }
]);

How do I do it and where could I put this code so it runs one time during the start of the app?

If you wanted those records to use in a template somewhere I’d consider putting them in the application route model hook. Whether or not you want to immediately save them to the backend is a separate concern, and up to you, but you could (in the application route) do something like:

model: function(){
  return RSVP.hash({
    record1: this.store.createRecord('product', ...),
    record2: this.store.createRecord('product', ...),
    record3: this.store.createRecord('product', ...),

  });
}

Or if you wanted an arbitrary number of records you could do something more like:

model: function(){
  let records = [];
  for(var i=0; i<10; i++) {
    records.push(this.store.createRecord('product', ...));
  }
  return RSVP.hash({
    records
  });
}

You can use the init method in the application route.

int() {
  this._super(...arguments);

  const store = this.get('store');

  store.createRecord( /* record details */ );
}

Using the model property it may run more than once. Init only gets called once ever. Until the app reinitializes.

1 Like

you can use push or pushPayload

Thank you all for your ideas @dknutsen, @Josh_Messer & @CezaryH!
:+1: