How to create a multidimensional record in ember.js?

Member

by domenico , in category: Javascript , 4 months ago

How to create a multidimensional record in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 4 months ago

@domenico 

In Ember.js, you can create a multidimensional record by defining a model with nested attributes.


First, define the model with the nested attributes in your Ember app. For example, let's create a model called "Parent" with nested attributes "child" and "grandchild" like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// app/models/parent.js

import Model, { attr, hasMany } from '@ember-data/model';

export default class ParentModel extends Model {
  @attr('string') name;
  @hasMany('child') children;
}

// app/models/child.js

import Model, { attr, belongsTo } from '@ember-data/model';

export default class ChildModel extends Model {
  @attr('string') name;
  @belongsTo('parent') parent;
  @hasMany('grandchild') grandchildren;
}

// app/models/grandchild.js

import Model, { attr, belongsTo } from '@ember-data/model';

export default class GrandChildModel extends Model {
  @attr('string') name;
  @belongsTo('child') parent;
}


Then, you can create new records for each model and associate them together as needed. For example, to create a new "Parent" record with a "Child" and a "Grandchild" record, you can do the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let parent = this.store.createRecord('parent', { name: 'Parent' });
let child = this.store.createRecord('child', { name: 'Child', parent: parent });
let grandchild = this.store.createRecord('grandchild', { name: 'Grandchild', parent: child });

parent.children.pushObject(child);
child.children.pushObject(grandchild);

// Save the records
await parent.save();
await child.save();
await grandchild.save();


This way, you have created a multidimensional record in Ember.js with nested attributes and multiple levels of relationships between the records.