3

I have a model named 'someModel' is as follows

import DS from 'ember-data';

export default DS.Model.extend({
  type: DS.attr('string'),
  email: DS.attr('string'),
  days: DS.attr('number'),
  isInstant: DS.attr('boolean'),
  cutHours: DS.attr('number')
});

and by default I need an array of 4 records of this model with default values as follows

"someModel": [{
      "type": "Booking",
      "email": "sunny.wayne@some.com,mahela.jayawardane@some.com",
      "isInstant": true,
      "cutHours": 72,
      "days": -1
    },
    {
      "type": "Booking",
      "email": "",
      "isInstant": false,
      "cutHours": 72,
      "days": -1
    },
    {
      "type": "Arrival",
      "email": "mahela.jayawardane@some.com",
      "isInstant": false,
      "cutHours": 72,
      "days": 1
    },
    {
      "type": "Cancellation",
      "email": "sunny.wayne@some.com",
      "isInstant": false,
      "cutHours": 72,
      "days": -1
    }
  ]

Whats the ideal way to do this? I looked at the createRecord, but only one record can be created at a time. My backend logic expecting the data to be in the above format and I will also have to update the 4 records that are created depending on the user action.

1 Answers1

0

Wrap your "someModel" with another model in a hasMany relationship.

Create another model, lets call it "parentModel" for our understanding. In its model definition, add the "someModel" as a property with hasMany relation.

parentModel.js

export default DS.Model.extend({
  someModel: DS.attr('someModel')
});

Now create a parentModel record and add as many as someModel records to it and save the parentModel.

let pModel = this.get("store").createRecord("parentModel");
pModel.get("someModel").addObject(this.get("store").createRecord("someModel", {
 type: "Booking",
 email: "sunny.wayne@some.com,mahela.jayawardane@some.com",
 isInstant: true,
 cutHours: 72,
 days: -1
}));
pModel.save();

Looking at the JSON structure that you had provided, you need to use JSONSerializer and EmbeddedRecordsMixin to get the someModel json in your response. Also make sure that "id" are retured for record of someModel in the response.

The request formed by ember would be like this

{
 "someModel": [{
   "type": "Booking",
   "email": "sunny.wayne@some.com,mahela.jayawardane@some.com",
   "isInstant": true,
   "cutHours": 72,
   "days": -1
 }]
}
r4M
  • 11
  • 3