Skip to content

Instantly share code, notes, and snippets.

@sukima
Forked from Alonski/controllers.application.js
Created March 16, 2019 12:03
Show Gist options
  • Save sukima/befb5f22f0171368dcc859d23117b4a0 to your computer and use it in GitHub Desktop.
Save sukima/befb5f22f0171368dcc859d23117b4a0 to your computer and use it in GitHub Desktop.
ember-data 3.7 relationships
import Controller from '@ember/controller';
import { reads } from '@ember/object/computed';
export default Controller.extend({
children: reads('model'),
actions: {
clickChild(child) {
child.parent.then(parent => {
console.log(parent.name);
});
}
}
});
export default function() {
this.resource('parent');
this.resource('child');
}
import { Factory } from 'ember-cli-mirage';
export default Factory.extend({
name(i) { return `Child-${i}`; }
});
import { Factory } from 'ember-cli-mirage';
export default Factory.extend({
name(i) { return `Parent-${i}`; }
});
export default function(server) {
let parent = server.create('parent');
server.createList('child', 10, { parent });
}
import { JSONAPISerializer } from 'ember-cli-mirage';
export default JSONAPISerializer.extend({
alwaysIncludeLinkageData: true,
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';
export default Model.extend({
name: attr('string'),
parent: belongsTo('parent')
});
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';
export default Model.extend({
name: attr('string'),
children: hasMany('child')
});
import Route from '@ember/routing/route';
export default Route.extend({
model() {
return this.store.findAll('child');
}
});
<ol>
<li>Open Dev Tools</li>
<li>Click on one of the items below</li>
<li>Realize parent is defined as an asynchronous request and somehow your code needs to wait for it to resolve before it can be used</li>
<li>Use <code>.then</code> or <code>async</code>/<code>await</code> just like promises so that the value is available when you need it</li>
<li>Profit</li>
</ol>
<ul>
{{#each children as |child|}}
<li {{action "clickChild" child}}>
{{child.name}}
-
{{#if child.parent.isPending}}
Loading&hellip;
{{else}}
{{child.parent.name}}
{{/if}}
</li>
{{else}}
<li>No Bars!</li>
{{/each}}
</ul>
{
"version": "0.15.1",
"EmberENV": {
"FEATURES": {}
},
"ENV": {
"ember-cli-mirage": {
"enabled": true
}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js",
"ember": "3.4.3",
"ember-template-compiler": "3.4.3",
"ember-testing": "3.4.3"
},
"addons": {
"ember-data": "3.7.0",
"ember-cli-mirage": "0.4.6"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment